Parsing with multiple delimiters in C
In C, what's the best way to parse a multi-delimited string? Let's say I have a string A,B,C*D
and you want to store these ABC D values. I'm not sure how to handle it *
elegantly, other than to store the last line C*D
and then parse that separately with *
.
If it were simple A,B,C,*D
I would use strtok () and ignore the first index *D
to get only D, but *
no comma in front of it, so I don't know what *
.
source to share
You can use multiple delimiters with strtok
, the second argument is a C string with a list of delimiters in it, not just one 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;
}
Output of this code:
A B C D
source to share