开发者

C function for separate a string in array of chars

I want to create a function 开发者_如何学JAVAto split a text using a separator in C. Two parameters text and separator will be passed to the function and the function should return an array of chars.

For example if the string is Hello Word of C and the separator is a white space.

Then the function should return,

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

as an array of chars.

Any suggestions?


Does strtok not suit your needs ?


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);


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 ?)

#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:

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


My solution (addressing comments by @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;
    }
}

Tested under Visual Studio 2008

Output:

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


I would recomend strsep. It's easier to understand than strtok, yet it dissects existing string, making it sequence of tokens. It's up to you to decide, if it needs to be copied first or not.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜