In C, what is the best way to parse a string with multiple delimiters? Say I have a string A,B,C*D
and want to store these values of A B C D. I'm not sure how to deal with the *
elegantly, other than to store the last string C*D
and then parse that separately with a *
delimiter.
If it was just A,B,C,*D
I'd use strtok() and ignore the first index of the *D
to get just D, but there is no comma before the *
so I don't know that *
is coming.
The function strtok breaks a string into a smaller strings, or tokens, using a set of delimiters. The string of delimiters may contain one or more delimiters and different delimiter strings may be used with each call to strtok .
Because strtok() modifies the initial string to be parsed, the string is subsequently unsafe and cannot be used in its original form. If you need to preserve the original string, copy it into a buffer and pass the address of the buffer to strtok() instead of the original string.
The strtok_r() function is a reentrant version of strtok() . The context pointer last must be provided on each call. The strtok_r() function may also be used to nest two parsing loops within one another, as long as separate context pointers are used.
The function strtok_r() returns a pointer to the first character of the first token, writes a NULL character into s immediately following the returned token, and updates the pointer to which lasts points.
You can use multiple delimiters with strtok
, the second argument is a C string with the list of delimiters in it, not just a single delimiter:
#include <stdio.h>
#include <string.h>
int main (void) {
char myStr[] = "A,B,C*D";
char *pChr = strtok (myStr, ",*");
while (pChr != NULL) {
printf ("%s ", pChr);
pChr = strtok (NULL, ",*");
}
putchar ('\n');
return 0;
}
The output of that code is:
A B C D
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With