代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void extract_fields(char* string) {
int count = 0;
char* token;
char* ptr;
int ii= 0;
// Counting the number of occurrences of "-"
for (int i = 0; string[i] != '\0'; i++) {
if (string[i] == '-') {
count++;
}
}
count++;
printf("%d\n",count);
// Extracting fields
ptr = string;
token = strtok(ptr, "-");
printf("Field %d before: %s\n", 1, token);
ii=atoi(token);
printf("%d",ii);
for (int i = 1; i < count; i++) {
token = strtok(NULL, "-");
printf("Field %d between: %s\n", i, token);
ptr = NULL;
}
}
int main() {
char string[] = "123-12-a-test-string";
extract_fields(string);
return 0;
}