C函数用于分隔字符数组中的字符串

我想创建一个函数来使用C中的分隔符拆分文本。两个参数textseparator将传递给函数,函数应该返回一个array of chars

例如,如果字符串是Hello Word of C则分隔符是white space

那么函数应该返回,

  0. Hello 1. Word 2. of 3. C 

作为一组字符。

有什么建议?

strtok不适合您的需求吗?

正如其他人已经说过的那样:不要指望我们编写你的作业代码,但这里有一个提示:(如果你被允许修改输入字符串)想一想这里发生了什么:

 char *str = "Hello Word of C"; // Shouldn't that have been "World of C"??? str[5] = 0; printf(str); 

嗯,和abelenky一样的解决方案,但没有无用的废话和混淆测试代码(当某些东西 – 比如printf – 应该写两次,我没有引入一个虚拟布尔来避免它,没有我在某处读到类似的东西?)

 #include char* SplitString(char* str, char sep) { return str; } main() { char* input = "Hello Word of C"; char *output, *temp; char * field; char sep = ' '; int cnt = 1; output = SplitString(input, sep); field = output; for(temp = field; *temp; ++temp){ if (*temp == sep){ printf("%d.) %.*s\n", cnt++, temp-field, field); field = temp+1; } } printf("%d.) %.*s\n", cnt++, temp-field, field); } 

在Linux下使用gcc测试:

 1.) Hello 2.) Word 3.) of 4.) C 

我的解决方案(解决@kriss的评论)

 char* SplitString(char* str, char sep) { char* ret = str; for(ret = str; *str != '\0'; ++str) { if (*str == sep) { *str = '\001'; } } return ret; } void TestSplit(void) { char* input = _strdup("Hello Word of C"); char *output, *temp; bool done = false; output = SplitString(input, ' '); int cnt = 1; for( ; *output != '\0' && !done; ) { for(temp = output; *temp > '\001'; ++temp) ; if (*temp == '\000') done=true; *temp = '\000'; printf("%d.) %s\n", cnt++, output); output = ++temp; } } 

在Visual Studio 2008下测试

输出:

 1.) Hello 2.) Word 3.) of 4.) C