使用c中的分隔符拆分字符串[关闭]

问题描述 投票:-6回答:1

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

c string split
1个回答
3
投票

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

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

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

  1. 只有在第一次调用中你必须传递源(str),后续调用strtok必须与NULL一起传递
  2. Strtok修改了源代码。不要使用不可修改的字符串或字符串文字("this is a string literal"
  3. 由于前一点,您应该始终复制源代码。

简单的例子

#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, 
© www.soinside.com 2019 - 2024. All rights reserved.