Jan Turoň
Jan Turoň

Reputation: 32912

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

I need this simple split

Item one, Item2,  Item no. 3,Item 4
>
Item one
Item2
Item no.3
Item 4

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

Upvotes: 5

Views: 4438

Answers (2)

verbose
verbose

Reputation: 7917

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

Upvotes: 6

Steve Barnes
Steve Barnes

Reputation: 28405

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.

Upvotes: 0

Related Questions