在C中使用多个定界符进行解析 [英] Parsing with multiple delimiters, in C
问题描述
在C语言中,解析带有多个定界符的字符串的最佳方法是什么?假设我有一个字符串A,B,C*D
,并且想存储这些ABC D值.除了存储最后一个字符串C*D
,然后用a分别解析之外,我不确定如何优雅地处理*
. *
分隔符.
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.
如果只是A,B,C,*D
,我将使用strtok()并忽略*D
的第一个索引来获取D,但是*
之前没有逗号,所以我不知道*
即将来临.
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.
推荐答案
您可以将多个分隔符与strtok
一起使用,第二个参数是带有 list 中的定界符,而不仅仅是单个定界符:
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;
}
该代码的输出为:
A B C D
这篇关于在C中使用多个定界符进行解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!