![]() |
| ||
| Many times strtok is recommended for parsing a string; I don't care for strtok. Why?
sscanf to parse a string into fields delimited by a character (a semicolon in this case, but commas or tabs or others could be used as well).Thanks to figo2476 for pointing out an issue with a previous version! Thanks to dwks for asking why not to use strtok. |
#include <stdio.h> int main(void) { const char line[] = "2004/12/03 12:01:59;info1;info2;info3"; const char *ptr = line; char field [ 32 ]; int n; while ( sscanf(ptr, "%31[^;]%n", field, &n) == 1 ) { printf("field = \"%s\"\n", field); ptr += n; /* advance the pointer by the number of characters read */ if ( *ptr != ';' ) { break; /* didn't find an expected delimiter, done? */ } ++ptr; /* skip the delimiter */ } return 0; } /* my output field = "2004/12/03 12:01:59" field = "info1" field = "info2" field = "info3" */