Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing with multiple delimiters, in C

In C, what is the best way to parse a string with multiple delimiters? Say I have a string A,B,C*D and want to store these values of A B C D. I'm not sure how to deal with the * elegantly, other than to store the last string C*D and then parse that separately with a * delimiter.

If it was just A,B,C,*D I'd use strtok() and ignore the first index of the *D to get just D, but there is no comma before the * so I don't know that * is coming.

like image 752
P B Avatar asked Jan 06 '15 02:01

P B


People also ask

Can you strtok with multiple delimiters?

The function strtok breaks a string into a smaller strings, or tokens, using a set of delimiters. The string of delimiters may contain one or more delimiters and different delimiter strings may be used with each call to strtok .

Why is strtok unsafe?

Because strtok() modifies the initial string to be parsed, the string is subsequently unsafe and cannot be used in its original form. If you need to preserve the original string, copy it into a buffer and pass the address of the buffer to strtok() instead of the original string.

What is the difference between strtok and strtok_r?

The strtok_r() function is a reentrant version of strtok() . The context pointer last must be provided on each call. The strtok_r() function may also be used to nest two parsing loops within one another, as long as separate context pointers are used.

What is strtok_r in C?

The function strtok_r() returns a pointer to the first character of the first token, writes a NULL character into s immediately following the returned token, and updates the pointer to which lasts points.


1 Answers

You can use multiple delimiters with strtok, the second argument is a C string with the list of delimiters in it, not just a single delimiter:

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

int main (void) {
    char myStr[] = "A,B,C*D";

    char *pChr = strtok (myStr, ",*");
    while (pChr != NULL) {
        printf ("%s ", pChr);
        pChr = strtok (NULL, ",*");
    }
    putchar ('\n');

    return 0;
}

The output of that code is:

A B C D
like image 130
paxdiablo Avatar answered Sep 30 '22 21:09

paxdiablo