【问题标题】:How to use strtok to separate specific string to array by two delimiter如何使用 strtok 通过两个分隔符将特定字符串分隔为数组
【发布时间】:2015-01-25 03:18:38
【问题描述】:

我有这样的字符串+100+200,300+500+400,700,900。我需要通过两个不同的符号'+'',' 将字符串拆分为数组,所以我想得到Aid = 100 和它的孩子arrayA [200, 300]B 的@ 987654329@ 是孩子 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;
}  

【问题讨论】:

  • 你可以使用strpbrk(),但我认为你应该使用2 strtok_rs

标签: c split strtok


【解决方案1】:

检查一下

#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;
}

我认为这是你需要的。

【讨论】:

  • 谢谢@iharob,这正是我所需要的。这是我从不知道的漂亮技巧。我会尝试理解 strtok_r。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-06
相关资源
最近更新 更多