[英]Split line into array of words + 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”从“ str”复制到tmp变量中? 这是我现在可以想到的最好方法,也许这是一个糟糕的主意。 如果是这样,我很乐意获得一些文档或有关更好方法的提示。
您应该签出C库函数strtok 。 您只需将要分解的字符串和分隔符字符串提供给它。
这是一个工作原理的示例(摘自链接网站):
#include <stdio.h>
#include <string.h>
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中的下一个元素。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.