C语言中如何从含可变站点的字符数组提取固定格式数字段
Alright, let's break this down. Since you can't rely on regex or shell tools, we'll use pure C standard library functions and basic string checks—nothing fancy, just straightforward logic that fits into your file retrieval proxy.
First, let's recap your problem: you have a string like www.google.com 20200929094403, where the timestamp is always a fixed 14-digit sequence (YYYYMMDDhhmmss), but the preceding site part varies in length. We need to yank that 14-digit chunk into a separate char array.
C doesn't have a direct equivalent to C#'s ParseInt for this exact scenario, but we can use simple character checks and string copying to get the job done. Here are two reliable approaches depending on your specific use case:
Approach 1: Extract from the End (Common for Log/Tagged Formats)
If your timestamp is always at the end of the string (like in your example), this is the most efficient method. We'll grab the last 14 characters, first verifying they're all digits to avoid errors.
#include <stdio.h> #include <string.h> #include <ctype.h> int main() { char input_str[] = "www.google.com 20200929094403"; char timestamp[15]; // 14 digits + null terminator int str_len = strlen(input_str); // First, make sure the string is long enough to hold a 14-digit timestamp if (str_len >= 14) { int timestamp_start = str_len - 14; int is_valid_timestamp = 1; // Verify every character in the last 14 positions is a digit for (int i = timestamp_start; i < str_len; i++) { if (!isdigit(input_str[i])) { is_valid_timestamp = 0; break; } } if (is_valid_timestamp) { // Copy the 14 digits to the timestamp array strncpy(timestamp, input_str + timestamp_start, 14); timestamp[14] = '\0'; // Critical: manually add null terminator (strncpy doesn't always do this) printf("Extracted timestamp: %s\n", timestamp); } else { printf("Error: Last 14 characters aren't all digits.\n"); } } else { printf("Error: String is too short to contain a 14-digit timestamp.\n"); } return 0; }
Key Notes:
- We use
isdigit()from<ctype.h>to validate each character—this ensures we don't accidentally grab non-digit characters. - Always add the null terminator
'\0'after copying! C strings rely on this to be recognized properly;strncpywon't add it automatically if the source length matches the copy length.
Approach 2: Find the First 14-Digit Sequence (General Case)
If your timestamp could appear anywhere in the string (not just the end), we'll scan the entire string to find the first run of 14 consecutive digits.
#include <stdio.h> #include <string.h> #include <ctype.h> int main() { char input_str[] = "www.google.com 20200929094403"; char timestamp[15]; int str_len = strlen(input_str); int found = 0; // Loop through the string, stopping when we have at least 14 characters left for (int i = 0; i <= str_len - 14; i++) { int is_valid = 1; // Check if the next 14 characters are all digits for (int j = 0; j < 14; j++) { if (!isdigit(input_str[i + j])) { is_valid = 0; break; } } if (is_valid) { // Copy the valid sequence strncpy(timestamp, input_str + i, 14); timestamp[14] = '\0'; printf("Extracted timestamp: %s\n", timestamp); found = 1; break; // Remove this if you need to find ALL 14-digit sequences } } if (!found) { printf("Error: No valid 14-digit timestamp found.\n"); } return 0; }
Key Notes:
- This loop stops early if it finds a valid sequence—remove the
breakif you need to collect all 14-digit chunks in the string. - We only loop up to
str_len -14because we need 14 characters remaining to form the timestamp.
Bonus: Convert the Timestamp String to a Numeric Value
If you need to work with the timestamp as a number (instead of a string), you can use sscanf() or strtoll() (for 64-bit integers, since 14 digits fit in a long long):
// Using sscanf long long timestamp_num; sscanf(timestamp, "%lld", ×tamp_num); printf("Timestamp as numeric value: %lld\n", timestamp_num); // Using strtoll (more robust for error checking) char *end_ptr; long long ts_num = strtoll(timestamp, &end_ptr, 10); if (end_ptr == timestamp + 14) { // Ensures all 14 characters were converted printf("Timestamp as numeric value: %lld\n", ts_num); } else { printf("Error: Failed to convert timestamp to number.\n"); }
Both methods work, but strtoll gives you better error checking to confirm the entire string was converted to a number.
内容的提问来源于stack exchange,提问作者MegalomaniacGT

