如何使用strtok将特定字符串分隔为两个分隔符

时间:2015-01-25 03:18:38

标签: c split strtok

我有像+100+200,300+500+400,700,900这样的字符串。我需要通过两个不同的符号'+'','将字符串拆分为数组,因此我希望得到A' id = 100并且它是'小孩arrayA [200, 300]B' id = 500及其小孩arrayB [400,700,900]

最好的方法是什么?

感谢。

我有示例代码:

#include <stdio.h>
#include <string.h>

typedef struct _example_s {
    unsigned short id;
    unsigned short child_id[5];
} example_t;

int main(void)
{
    example_t ex_ary[2]; //it means A and B

    char msg[30] = "+100+200,300+500+400,700,900";

    char *result = NULL;

    result = strtok(msg, "+,");

    while(result != NULL ) {
        printf("%s\n", result);
        result = strtok(NULL, "+,");
    }

    return 0;
}  

1 个答案:

答案 0 :(得分:0)

检查

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

typedef struct _example_s {
    unsigned short id;
    unsigned short child_id[5];
} example_t;

int main(void)
{
    example_t ex_ary[2]; //it means A and B
    size_t index;
    char msg[30] = "+100+200,300+500+400,700,900";
    char *result = NULL;
    char *plusSign;

    memset(ex_ary, 0, sizeof(ex_ary));

    index  = 0;
    result = strtok_r(msg, "+", &plusSign);
    while (result != NULL )
    {
        char  *comma;
        char  *array;
        size_t element;

        ex_ary[index].id = strtol(result, NULL, 10);
        result           = strtok_r(NULL, "+", &plusSign);
        element          = 0;
        if (result != NULL)
        {
            array = strtok_r(result, ",", &comma);
            while (array != NULL)
            {
                ex_ary[index].child_id[element++] = strtol(array, NULL, 10);
                array                             = strtok_r(NULL, ",", &comma);
            }
        }
        index += 1;
        result = strtok_r(NULL, "+", &plusSign);
    }

    for (index = 0 ; index < 2 ; ++index)
    {
        size_t i;

        printf("id: %d\n", ex_ary[index].id);
        for (i = 0 ; i < 5 ; ++i)
        {
            printf("\t%d\n", ex_ary[index].child_id[i]);
        }
    }
    return 0;
}

我认为这就是你所需要的。