5

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?

Jan Turoň
  • 31,451
  • 23
  • 125
  • 169

2 Answers2

6

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
verbose
  • 7,827
  • 1
  • 25
  • 40
  • 1
    I'd recommend to use `strtok_r` instead of `strtok` to avoid funny bugs in multithreaded environments. – DarkDust Sep 09 '13 at 11:31
  • `strtok_r` isn't standard C, is it? I don't know whether it would compile on a Windows machine, for example. See http://stackoverflow.com/questions/9021502/whats-the-difference-between-strtok-r-and-strtok-s-in-c – verbose Sep 09 '13 at 17:55
  • what does the `while (buffer && *buffer == '\040')` line do? – ocean800 Sep 30 '15 at 03:08
  • `while (buffer)` checks that the character in the buffer is not NUL, i.e., that we are not at the end of the string. `(*buffer == '\040')` checks that the character in the buffer is a space. So as long we are not at the end of the string, AND the current character is a space, we move to the next char. – verbose Oct 01 '15 at 03:49
0

You can step through the string looking for , or 0x00 and replace any , with a 0x00 then step past any spaces to find the start of the next string. Regex is a lot easier.

Steve Barnes
  • 27,618
  • 6
  • 63
  • 73