[英]How to split string with special characters multiple times or in a continuous manner in C
I have the following string,我有以下字符串,
#98727,72000,2500,2450,2200,999999,999999#2500,2450,2200,999999,999999#2500,2450,2200,999999,999999#2500,2450,2200,999999,999999#,
& am looking to split this entire string with special character #
. & 我希望用特殊字符
#
分割整个字符串。 In order to get the four #
separated string sets.为了得到四个
#
分隔的字符串集。
After that these separated string sets need to be split using ,
to get values like eg: 98727 alone.之后,这些分隔的字符串集需要使用
,
进行拆分,
以单独获得例如: 98727 之类的值。
I've finished separating first set of values using #
& ,
with the below code.我已经完成分离第一套使用值
#
& ,
用下面的代码。 But, it doesn't separating the second set.但是,它并没有将第二组分开。 What am I missing in this set of code to separate all sets & its values?
我在这组代码中缺少什么来分隔所有集合及其值?
char buffer[] = "#18115,72000,2500,2450,2200,999999,999999#2500,2450,2200,999999,999999#2500,2450,2200,999999,999999#2500,2450,2200,999999,999999#";
char *ptr = &buffer;
char *p;
for (p = strtok(ptr,""); p != NULL; p = strtok(NULL, ","))
{
printf("Set: %s\r\n", p);
char *n;
for (n = strtok(p,","); n != NULL; n = strtok(NULL, ","))
{
printf("%s\r\n", n);
}
}
And getting an output like this:并得到这样的输出:
Set: 18115,72000,2500,2450,2200,999999,999999
18115
72000
2500
2450
2200
999999
999999
Instead of first splitting by occurrences of #
and then by that of ,
, you could split by occurrence of #
or ,
at once using strpbrk()
.而是由发生第一剖开的
#
,然后通过的,
你可以通过发生分裂#
或者,
在一次使用strpbrk()
You could do something like你可以做类似的事情
char str[]="#98727,72000,2500,2450,2200,999999,999999#2500,2450,2200,999999,999999#2500,2450,2200,999999,999999#2500,2450,2200,999999,999999#,";
char *p;
char num_str[20][10];
int i=0;
for(p=str; (p=strpbrk(p, "#,"))!=NULL; )
{
while(*(++p)=='#' || *p==',');
if(*p=='\0')
{
break; //input string over
}
sscanf(p, "%9[^#,]", num_str[i++]);
printf("\n%s", num_str[i-1]);
}
A pointer p
is maintained which points to the next #
or ,
to be examined in the input string.一个指针
p
被维护,它指向下一个#
或,
要在输入字符串中检查。 strpbrk()
is used to find this pointer value. strpbrk()
用于查找此指针值。
strpbrk()
returns a pointer to the first occurrence of any character of a string in another string. strpbrk()
返回一个指针,指向另一个字符串中字符串的任何字符的第一次出现。
After finding the value of p
, it is incremented so that it points to the character after the #
or ,
and if this character is also one of those, you keep on incrementing till another character is found.找到
p
的值后,它会递增,以便它指向#
或 之后的字符,
如果该字符也是其中之一,则继续递增,直到找到另一个字符。 If this character is the nul character denoting the end of string, we exit the outer loop.如果这个字符是表示字符串结束的空字符,我们退出外循环。
sscanf()
is used to extract the characters till the next #
or ,
. sscanf()
用于提取字符直到下一个#
或,
。
%9[^#,]
reads till but not including the next #
or ,
. %9[^#,]
读取直到但不包括下一个#
或,
。
PS: The \\r
in printf("Set: %s\\r\\n", p);
PS:该
\\r
中printf("Set: %s\\r\\n", p);
is superfluous.是多余的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.