我正在尝试编写一个程序,它迭代一个字符数组(其中包含一个句子),并将该句子中的单词分配给另一个数组,跳过空格(这就是我们知道单独单词的方式),然后打印这些文字。
例如,我的字符数组是:
{'t','h','e',' ','f','o','x',' ','r','u','n','s','\0',}
我希望我的函数将单词分配给一个数组,称之为words
,一次一个,跳过空格,然后将单词一一打印出来。
我尝试过这个:
for (i = 0, x = 0; a[i] != '\0'; i++, x++){
if (a[i] != ' '){
words[x] = a[i];
}
else{
words[x] = '\0';
printf("%s\n", words);
x=0;
i++;
continue;
}
}
printf("%s\n", words);
但是当我运行它时,它只打印出s
最佳答案
我的建议是 strtok()
。这会很容易。
想法:
- 使用
strtok()
和空格' '
作为分隔符来找出每个出现的单词。 - 使用
strcpy()
复制将返回的token
(words)复制到word
数组.
注意:
I want my function to assign the words to an array, call it words, one at a time, skipping over the spaces, the words then printed one by one.
您当前的代码看起来并没有做同样的事情。
- 您可以摆脱对输入字符串进行迭代的
for
循环。 - 您需要在同一输入上继续执行
strtok()
,直到它返回NULL
。 words[x]
需要是char *
(具有正确分配的内存)或char []
(数组)来保存每个从输入字符串中找到单词,然后逐一打印。
关于c - 迭代字符数组,同时跳过空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29466132/