gpt4 book ai didi

c - 如何使用 strtok 通过两个分隔符分隔特定字符串到数组

转载 作者:行者123 更新时间:2023-11-30 17:22:02 25 4
gpt4 key购买 nike

我有这样的字符串+100+200,300+500+400,700,900。我需要用两个不同的符号 '+'',' 将字符串拆分为数组,所以我想获得 Aid = 100 及其子 arrayA [200, 300]Bid = 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;
}

最佳答案

检查这个

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

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

关于c - 如何使用 strtok 通过两个分隔符分隔特定字符串到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28132861/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com