C语言 如何解析以逗号分隔的字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15822660/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 05:57:35  来源:igfitidea点击:

How to parse a string separated by commas?

c

提问by Ammar

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

I want to store each number into an int variable and then print it out.

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

For example the output becomes like this.

例如输出变成这样。

Value1 = 1

值 1 = 1

value2 = 5

值 2 = 5

Value3= 95

值 3 = 95

value4 = 255

值 4 = 255

And I want to do this inside a loop, so If I have more than 4 values in strings, I should be able to get the rest of the values.

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

I would like to see an example for this one. I know this is very basic to many of you, but I find it a little challenging.

我想看看这个例子。我知道这对你们中的许多人来说是非常基础的,但我觉得这有点挑战。

Thank you

谢谢

回答by gongzhitaao

Modified from cplusplusstrtokexample:

修改自cplusplusstrtok示例:

#include <stdio.h>
#include <string.h>
#include <stdlib.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;
}

回答by Edward Goodson

I don't know the functions mentioned in the comments above but to do what you want in the way you are asking I would try this or something similar.

我不知道上面评论中提到的功能,但要按照您要求的方式做您想做的事情,我会尝试此操作或类似的操作。

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

回答by iain

If you don't have a modifiable string, I would use strchr. Search for the next ,and then scan like that

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

#define MAX_LENGTH_OF_NUMBER 9
char *string = "1,5,95,255";
char *comma;
char *position;
// number has 9 digits plus ##代码##
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] = '##代码##';
    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