使用c中的分隔符拆分字符串

时间:2017-12-28 18:27:41

标签: c string split

我的输入字符串是1,2,3:4,5,6:7,5,8 首先,我需要拆分1,2,3套机智:分隔符。然后我再次需要拆分1 2 3,分隔符。所以我需要做外部拆分和内部拆分直到输入字符串结束。请用一些例子解释我

1 个答案:

答案 0 :(得分:3)

正如coderredoc所说,strtok是你需要的功能。

#include <string.h>
char *strtok(char *str, const char *delim);

strtok有一些 你要记住的怪癖:

  1. 只有在第一次通话中,你才必须传递来源(str) 必须使用strtok

  2. 传递NULL的来电
  3. Strtok修改了来源。不要使用不可修改的字符串或字符串 文字("this is a string literal"

  4. 由于前一点,您应该始终复制该来源。

  5. 简单示例

    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    int main(void)
    {
        const char *text = "Hello:World:!";
    
        char *tmp = strdup(text);
        if(tmp == NULL)
            return 1; // no more memory
    
        char *token = strtok(tmp, ":");
    
        if(token == NULL)
        {
            free(tmp);
            printf("No tokens\n");
            return 1;
        }
    
        printf("Token: '%s'\n", token);
    
        while(token = strtok(NULL, ":"))
            printf("Token: '%s'\n", token);
    
        free(tmp);
    
        return 0;
    }
    

    预期输出

    Token: 'Hello'
    Token: 'World'
    Token: '!'
    

    <强>更新

    如果您需要嵌套strtok,则应使用前面提到的strtok_r。 以下是我上面示例的更新。如果我没有弄错的话,input会有 与你的格式相同(或多或少,我的设置尺寸不同,但原理相同)

    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    int main(void)
    {
        const char *input ="v1,v2,v3,v4,v5:w1,w2,w3,w4,w5:x1,x2,x3,x4:y1,y2,y3,y4,y5,y6";
    
        char *input_copy = strdup(input);
        char *set_track, *elem_track;  // keep track for strtok_r
        char *set, *value;
    
        char *_input = input_copy;
    
        int setnum = 0;
    
        while(set = strtok_r(_input, ":", &set_track))
        {
            _input = NULL; // for subsequent calls of strtok_r
    
            printf("Set %d contains: ", ++setnum);
    
            // in this case I don't care about strtok messing with the input
            char *_set_input = set; // same trick as above
            while(value = strtok_r(_set_input, ",", &elem_track))
            {
                _set_input = NULL; // for subsequent calls of strtok_r
                printf("%s, ", value);
            }
    
            puts("");
        }
    
        free(input_copy);
        return 0;
    }
    

    预期输出

    Set 1 contains: v1, v2, v3, v4, v5, 
    Set 2 contains: w1, w2, w3, w4, w5, 
    Set 3 contains: x1, x2, x3, x4, 
    Set 4 contains: y1, y2, y3, y4, y5, y6, 
    
相关问题