C语言编程。读取输入并将其解析为单词
我正在用C编写一个小程序,它将从控制台读取输入。然后将其放入一个字符数组中。之后,我需要将数组拆分为单词。我不知道该怎么做。到目前为止,我已经将输入放入了一个char数组中。我需要知道是否有一种基于空白字符标记的方法。或者关于如何处理这个问题的任何其他建议。谢谢 样本: 输入:这只是一个测试 数组:[t,h,i,s,i,s,o,n,l,y,a,t,e,s,t,null] 我想得到一个字符串数组[这是,仅是,a,test,null]C语言编程。读取输入并将其解析为单词,c,arrays,char,C,Arrays,Char,我正在用C编写一个小程序,它将从控制台读取输入。然后将其放入一个字符数组中。之后,我需要将数组拆分为单词。我不知道该怎么做。到目前为止,我已经将输入放入了一个char数组中。我需要知道是否有一种基于空白字符标记的方法。或者关于如何处理这个问题的任何其他建议。谢谢 样本: 输入:这只是一个测试 数组:[t,h,i,s,i,s,o,n,l,y,a,t,e,s,t,null] 我想得到一个字符串数组[这是,仅是,a,test,null] main() { char msg[50], ch;
main() {
char msg[50], ch;
int i = 0;
printf("***Reading words in your input*****\n\n");
printf("Type something terminated by ENTER button\n");
while ((ch = getchar()) != '\n')
msg[i++] = ch;
msg[i] = '\0';
i = 0;
while (msg[i] != '\0')
putchar(msg[i++]);
printf("\n");
}
是,使用strtok功能:
char* token = strtok(msg, " ");
while (token != NULL) {
printf("%s", token);
token = strtok(NULL, " ");
}
如果您希望读取所有单词直到文件结束(不在换行符处停止),则此操作更简单:
#include <stdio.h>
int main(){
char b[999];
while (scanf("%s",b)==1)
puts(b);
return 0;
}
#包括
int main(){
charb[999];
而(scanf(“%s”,b)==1)
出售(b);
返回0;
}
scanf的返回值是成功解析的字段数,即EOF。空格用于分隔“%s”字段,因此您可以获得所需的标记。当然,如果你确实先读了一行,你仍然可以使用sscanf
如果您想累积字符串数组,而不是一个接一个地处理它们(“上面的puts(b)”),那么您需要使用realloc、malloc、strcpy和strlen。固定大小的缓冲区很糟糕。C没有您使用的字符串。C有字符数组 如果需要字符串数组。。。您可以使用类似于字符数组的内容 但是每个数组都有一个预先确定的大小,您不能添加更多的“字符串”,也不能使它们比可用空间长。另一个选项(而不是字符数组)是使用malloc()和friends中的指针和内存(关于poonters、malloc()和friends的讨论将留待下次讨论) 要定义字符数组并按空格拆分句子,可以执行以下操作
char array_of_string[10][6]; /* 10 strings of a maximum of 5 characters each, plus the NUL */
char msg[50] = "this is a test";
/* now split the msg and put the words in array_of_string */
int string_num = 0;
int word_size = 0;
int msg_index = 0;
while (msg[msg_index] != '\0') {
if (msg[msg_index] != ' ') {
/* add the character to the proper place in array_of_string */
array_of_string[string_num][word_size] = msg[msg_index];
/* and update word_size for next time through the loop */
word_size++; /* needs check for reserved word size (5) */
} else {
/* a space! */
/* first, terminate the current word */
array_of_string[string_num][word_size] = '\0';
/* prepare to start the next word */
string_num++; /* needs check for reserved number of "strings" (10) */
word_size = 0;
}
}
/* array_of_string[0] is now "this"
* array_of_string[1] is now "is"
* ...
*/
需要注意的一点是strtok()保持静态,因此它不是线程安全的。如果出现问题,请使用strtok_r()。strtok()会更改原始字符串。这可能也是一个问题;如果这确实是一个问题,您可以
strcopy
原始字符串。有关一般问题解析问题的资源,请参阅。