Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse a string separated by commas? [duplicate]

Tags:

c

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

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

For example the output becomes like this.

Value1 = 1

value2 = 5

Value3= 95

value4 = 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.

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

like image 544
Ammar Avatar asked Apr 04 '13 22:04

Ammar


People also ask

How do you remove duplicates from a comma separated string?

We can do this with the SPLIT function. This function returns a row of cells divided based on the delimiter. To remove duplicate values, we have to use the UNIQUE function. Since the UNIQUE function works for cells in different rows, we'll have to transpose our SPLIT output using the TRANSPOSE function.

How do you parse a comma separated string in C++?

Program to Parse a comma separated string in C++Get the substring if the string from starting point to the first appearance of ', ' using getline() method. This will give the word in the substring. Now store this word in the vector. This word is now removed from the stream and stored in the vector.

How do you parse a comma delimited string in Java?

In order to parse a comma-delimited String, you can just provide a "," as a delimiter and it will return an array of String containing individual values. The split() function internally uses Java's regular expression API (java. util. regex) to do its job.

How do you split a string by a space and a comma?

To split a string by space or comma, pass the following regular expression to the split() method - /[, ]+/ . The method will split the string on each occurrence of a space or comma and return an array containing the substrings.


1 Answers

Modified from cplusplus strtok example:

#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;
}
like image 65
gongzhitaao Avatar answered Nov 14 '22 23:11

gongzhitaao