Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split string by commas optionally followed by spaces without regex?

Tags:

c

parsing

I need this simple split

Item one, Item2,  Item no. 3,Item 4
>
Item one
Item2
Item no.3
Item 4
  • I know I can use %*[, ] format in scanf to ignore comma and spaces, but this is not accurate: the separator should be exactly one comma optionally followed by spaces.
  • I think I can't use strtok either, since space alone is not a delimiter.

Do I really need regex here, or is there any effective short way to encode this?

like image 955
Jan Turoň Avatar asked Sep 09 '13 10:09

Jan Turoň


1 Answers

How about something like:

char inputStr[] = "Item one, Item2,  Item no. 3,Item 4";
char* buffer;

buffer = strtok (inputStr, ",");

while (buffer) {
    printf ("%s\n", buffer);          // process token
    buffer = strtok (NULL, ",");
    while (buffer && *buffer == '\040')
        buffer++;
}

Output:

Item one
Item2
Item no. 3
Item 4
like image 147
verbose Avatar answered Nov 01 '22 15:11

verbose