在 C 中使用 Strtok 获取字符串
我想将一个字符串分成三部分。
gets(input);
printf("\n%s\n",input);
first = strtok (input, " ");
second = strtok ( NULL, " " );
others = "";
while(input != NULL){
tmp = strtok ( NULL, " " );
strcat(others,tmp);
}
像这样...所以我想将第一个单词、第二个单词放入字符串中,将其他单词放入字符串中。此代码失败,我该如何解决这个问题?
I want to split a string to 3 parts.
gets(input);
printf("\n%s\n",input);
first = strtok (input, " ");
second = strtok ( NULL, " " );
others = "";
while(input != NULL){
tmp = strtok ( NULL, " " );
strcat(others,tmp);
}
like this... So i want to get first word, second word into a string and others in a string. This code fails, how can i resolve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
C 中的字符串并不神奇,它们是字符数组。您不能只是将
strcat
转换为只读的空字符串。相反,您必须提供自己的目标字符串:您还使用了
input
和tmp
错误;在处理之前,您应该检查strtok
的结果。这有点危险,因为您无法控制结果字符串的长度。您应该使用
strncat
来代替,但这意味着您还必须计算附加字符的数量。Strings in C aren't magic, they're character arrays. You cannot just
strcat
into a readonly, empty string. Rather, you have to provide your own target string:You also used
input
andtmp
wrong; you should be checking the result ofstrtok
before processing it.This is somewhat dangerous since you have no control over the resulting string length. You should use
strncat
instead, but that means you'll also have to keep count of the appended characters.您应该检查
此外,“其他”没有指向任何分配的内存,因此我预计它会崩溃,直到您解决该问题。
You should be checking
Also, "others" doesn't point to any allocated memory, so I'd expect this to crash until you fix that.
该代码有几个缺陷:
假设
others
是一个字符数组,您不能以这种方式使用它。您必须分配足够的内存。另外,条件应该是
另外,语句 Second = strtok ( NULL, " " ); 是多余的,您应该在循环内执行此操作。
There are several flaws with the code:
Assuming,
others
is a character array, you can't work with it in that manner. You have to allocate sufficient memory.Also, the condition should be
Also, the statment
second = strtok ( NULL, " " );
is redundant, you should be doing this inside the loop.