在 C 中使用 Strtok 获取字符串

发布于 2024-12-09 04:50:20 字数 306 浏览 1 评论 0原文

我想将一个字符串分成三部分。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

伪装你 2024-12-16 04:50:20

C 中的字符串并不神奇,它们是字符数组。您不能只是将 strcat 转换为只读的空字符串。相反,您必须提供自己的目标字符串:

char others[1000] = { 0 };
char * tmp;

// ...

while ((tmp = strtok(NULL, " ")) != NULL)
{
  strcat(others, tmp);
}

您还使用了 inputtmp 错误;在处理之前,您应该检查 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:

char others[1000] = { 0 };
char * tmp;

// ...

while ((tmp = strtok(NULL, " ")) != NULL)
{
  strcat(others, tmp);
}

You also used input and tmp wrong; you should be checking the result of strtok 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.

风筝在阴天搁浅。 2024-12-16 04:50:20

您应该检查

while (tmp != NULL)

此外,“其他”没有指向任何分配的内存,因此我预计它会崩溃,直到您解决该问题。

You should be checking

while (tmp != NULL)

Also, "others" doesn't point to any allocated memory, so I'd expect this to crash until you fix that.

茶色山野 2024-12-16 04:50:20

该代码有几个缺陷:

假设 others 是一个字符数组,您不能以这种方式使用它。您必须分配足够的内存。

另外,条件应该是

while(tmp != NULL)

另外,语句 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

while(tmp != NULL)

Also, the statment second = strtok ( NULL, " " ); is redundant, you should be doing this inside the loop.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文