C语言 用于在字符数组中分隔字符串的 C 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4319166/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C function for separate a string in array of chars
提问by pedrofernandes
I want to create a function to split a text using a separator in C.
Two parameters textand separatorwill be passed to the function and the function should return an array of chars.
我想创建一个函数来分割使用C.两个参数的分隔符文字text和separator将被传递给函数和函数返回的array of chars。
For example if the string is Hello Word of Cand the separator is a white space.
例如,如果字符串是Hello Word of C并且分隔符是white space.
Then the function should return,
然后函数应该返回,
0. Hello
1. Word
2. of
3. C
as an array of chars.
作为字符数组。
Any suggestions?
有什么建议?
回答by Bart
As someone else already said: do not expect us to write your homework code, but here's a hint: (if you're allowed to modify the input string) Think about what happens here:
正如其他人已经说过的:不要指望我们编写您的作业代码,但这里有一个提示:(如果您被允许修改输入字符串)想想这里会发生什么:
char *str = "Hello Word of C"; // Shouldn't that have been "World of C"???
str[5] = 0;
printf(str);
回答by kriss
Well, same solution as abelenky, but without the useless crap and obfuscation of test code (when something - like printf - should be written twice, I do not introduce a dummy boolean to avoid it, didn't have I read something like that somewhere ?)
嗯,与 abelenky 相同的解决方案,但没有无用的废话和测试代码的混淆(当某些东西 - 比如 printf - 应该写两次时,我没有引入一个虚拟布尔值来避免它,我没有在某处读过类似的东西?)
#include<stdio.h>
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);
}
Tested with gcc under Linux:
Linux下用gcc测试:
1.) Hello
2.) Word
3.) of
4.) C
回答by abelenky
My solution (addressing comments by @kriss)
我的解决方案(解决@kriss 的评论)
char* SplitString(char* str, char sep)
{
char* ret = str;
for(ret = str; *str != '1.) Hello
2.) Word
3.) of
4.) C
'; ++str)
{
if (*str == sep)
{
*str = '##代码##1';
}
}
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 != '##代码##' && !done; )
{
for(temp = output; *temp > '##代码##1'; ++temp) ;
if (*temp == '##代码##0') done=true;
*temp = '##代码##0';
printf("%d.) %s\n", cnt++, output);
output = ++temp;
}
}
Tested under Visual Studio 2008
在 Visual Studio 2008 下测试
Output:
输出:
##代码##
