Strtok with multiple delimiters

I tried to parse a line like:

"12 13 14   16"

for 5 numbers in an array.

I use strtok(string_above, " "), but strtok()will take these three empty characters as one. What can I do to prevent this?

+4
source share
1 answer

I liked doing this, it might be what you need. I did not test it extensively, but passed a simple test.

#include <stdio.h>
#include <string.h>
#include <ctype.h>

int
main(void)
{
    char string[] = "12 13 14   16";
    char *current;
    char *next;
    int done;
    current = string;
    done = 0;
    while (done == 0)
    {
        next = strchr(current, ' ');
        if (next == NULL)
            next = strchr(current, '\0');
        // If there are no more tokens, current[0] will be 
        // equal to 0 and (end == current) too
        done = (current[0] == '\0');
        if ((next != current) && (done == 0))
        {
            // We nul terminate it (replace the delimiter with nul)
            // so now, current is the token.
            next[0] = '\0';
            // Display the token
            printf("--%s--\n", current);
            // Restore the character
            next[0] = ' ';
            // Advance to the next characeter (for the next strchr())
            current = next + 1;
        }
        else if (*next++ == ' ') // If the next character is a space, 
        {                        // it a delimiter
            int spaces;
            int count;

            // Count the number of spaces to see 
            // if the space is a delimiter or a token
            spaces = 1;
            // Count the number of tokens
            count = 1;
            // While the current character is a space, we seek for a non-space
            while (isspace((unsigned char) *next) != 0)
            {
                next++;
                if (spaces % 2 == 0) // If it an even space (it a token)
                    count += 1;
                spaces++;
            }
            // If the spaces variable is not even 
            // there was no delimiter for the last
            // token consider this an input error
            if (spaces % 2 != 0)
                return -1;
            // Print the blanks as 0's
            for (int i = 0 ; i < count ; ++i)
                printf("--0--\n");
            // Advance to the next characeter (for the next strchr())
            current = next;
        }
    }
    return 0;
}
+2
source

Source: https://habr.com/ru/post/1618141/


All Articles