当我将分隔符指定为“,”时,为什么我strtok
在空格后拆分字符串?
问问题
2161 次
2 回答
7
我只能建议您做错了什么,尽管很难确切地说出是什么(在询问具体情况时,您通常应该发布您的代码)。示例程序,如下所示,似乎工作正常:
#include <stdio.h>
#include <string.h>
int main (void) {
char *s;
char str[] =
"This is a string,"
" with both spaces and commas,"
" for testing.";
printf ("[%s]\n", str);
s = strtok (str, ",");
while (s != NULL) {
printf (" [%s]\n", s);
s = strtok (NULL, ",");
}
return 0;
}
它输出:
[This is a string, with both spaces and commas, for testing.]
[This is a string]
[ with both spaces and commas]
[ for testing.]
立即浮现在脑海中的唯一可能性是,如果您使用" ,"
的是","
. 在这种情况下,你会得到:
[This is a string, with both spaces and commas, for testing.]
[This]
[is]
[a]
[string]
[with]
[both]
[spaces]
[and]
[commas]
[for]
[testing.]
于 2010-08-10T07:05:35.363 回答
0
谢谢!我环顾四周,发现问题出在我的 scanf 上,它没有读取用户输入的整行。看来我的 strtok 工作正常,但我用来匹配 strtok 的返回值的值是错误的。例如,我的 strtok 函数采用“Jeremy whitfield,Ronny Whitfield”并给了我“Jeremy Whitfield”和“Ronny Whitfield”。在我的程序中,我正在使用 scanf 来接收用户输入>“Ronny Whitfield”,它实际上只是在读取“Ronny”。所以这是我的scanf而不是strtok的问题。我的虚拟机每次打开时都会卡住,所以我现在无法访问我的代码。
于 2010-08-10T14:09:52.830 回答