将行拆分为单词+ C的数组

我试图将一行分成一系列单词,但我仍然坚持如何在C中这样做。我的C技能不是很好,所以我想不出一种方法来“执行”我的想法。 她是我迄今为止所拥有的:

int beginIndex = 0; int endIndex = 0; int maxWords = 10; while (1) { while (!isspace(str)) { endIndex++; } char *tmp = (string from 'str' from beginIndex to endIndex) arr[wordCnt] = tmp; wordCnt++; beginIndex = endIndex; if (wordCnt = maxWords) { return; } } 

在我的方法中,我收到(char * str,char * arr [10]),str是我想要在遇到空格时要拆分的行。 arr是我想要存储单词的数组。 有没有办法将我想要的’chunk’的’chunk’复制到我的tmp变量中? 这是我现在想到的最好的方式,也许这是一个糟糕的主意。 如果是这样,我很乐意获得一些更好的方法的文档或技巧。

 #include  #include  #include  #include  int split(char *str, char *arr[10]){ int beginIndex = 0; int endIndex; int maxWords = 10; int wordCnt = 0; while(1){ while(isspace(str[beginIndex])){ ++beginIndex; } if(str[beginIndex] == '\0') break; endIndex = beginIndex; while (str[endIndex] && !isspace(str[endIndex])){ ++endIndex; } int len = endIndex - beginIndex; char *tmp = calloc(len + 1, sizeof(char)); memcpy(tmp, &str[beginIndex], len); arr[wordCnt++] = tmp; beginIndex = endIndex; if (wordCnt == maxWords) break; } return wordCnt; } int main(void) { char *arr[10]; int i; int n = split("1st 2nd 3rd", arr); for(i = 0; i < n; ++i){ puts(arr[i]); free(arr[i]); } return 0; } 

你应该看看C库函数strtok 。 你只需要输入你想要分解的字符串和一串分隔符。

以下是它的工作原理示例(取自链接网站):

 #include  #include  int main () { char str[] ="- This, a sample string."; char * pch; printf ("Splitting string \"%s\" into tokens:\n",str); pch = strtok (str," ,.-"); while (pch != NULL) { printf ("%s\n",pch); pch = strtok (NULL, " ,.-"); } return 0; } 

在你的情况下,你不是打印每个字符串,而是将strtok返回的指针分配给数组arr中的下一个元素。