如何解析用逗号分隔的字符串?

时间:2013-04-04 22:11:16

标签: c

Char *strings = "1,5,95,255"

我想将每个数字存储到一个int变量中,然后将其打印出来。

例如输出变为这样。

Value1 = 1

value2 = 5

Value3 = 95

value4 = 255

我想在循环中执行此操作,因此如果我在字符串中有超过4个值,我应该能够获得其余的值。

我想看一个这个例子。我知道这对你们很多人来说非常基础,但我发现它有点挑战性。

谢谢

3 个答案:

答案 0 :(得分:7)

修改自cplusplus strtok示例:

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

int main ()
{
    char str[] ="1,2,3,4,5";
    char *pt;
    pt = strtok (str,",");
    while (pt != NULL) {
        int a = atoi(pt);
        printf("%d\n", a);
        pt = strtok (NULL, ",");
    }
    return 0;
}

答案 1 :(得分:0)

我不知道上面评论中提到的功能,但是按照你要求的方式做你想做的事我会尝试这个或类似的东西。

char *strings = "1,5,95,255";
char number;
int i = 0; 
int value = 1;

printf ("value%d = ", value);
value++; 

while (strings[i] != NULL) {
   number = string[i];
   i++;
   if (number == ',') 
       printf("\nvalue%d = ",value++);
   else 
       printf("%s",&number);
} 

答案 2 :(得分:0)

如果您没有可修改的字符串,我会使用strchr。搜索下一个,,然后像那样扫描

#define MAX_LENGTH_OF_NUMBER 9
char *string = "1,5,95,255";
char *comma;
char *position;
// number has 9 digits plus \0
char number[MAX_LENGTH_OF_NUMBER + 1];

comma = strchr (string, ',');
position = string;
while (comma) {
    int i = 0;

    while (position < comma && i <= MAX_LENGTH_OF_NUMBER) {
        number[i] = *position;
        i++;
        position++;
    }

    // Add a NULL to the end of the string
    number[i] = '\0';
    printf("Value is %d\n", atoi (number));

    // Position is now the comma, skip it past
    position++;
    comma = strchr (position, ',');
}

// Now there's no more commas in the string so the final value is simply the rest of the string
printf("Value is %d\n", atoi (position)l