Strtok? For comma seperated string

Hi! I want the args String in my cloud function to take different values separated with a comma. And put each values through a for loop. Can somone please explain me how i can do this. I have read about strtok but i dont understand it.

If your original string is a String object you can use these functions
https://docs.particle.io/reference/firmware/photon/#string-class

But I still prefer strtok() - what exactly isn’t clear? The way how you asked the question is a bit too open to answer concisely.

This is a site I usually recommend
http://www.cplusplus.com/reference/cstring/strtok/

sscanf() might also be useful to look at (just not for floats).

2 Likes

I don´t really understand how it works. Do you have an very simple example on how you would do it so i can understand the basics? :thinking:

Since strtok() takes a char* as its input, you first need to convert your String object to a char array; that can be done using the String function toCharArray(). For the first, use of strtok(), you pass in the char array that you’re parsing, and for all subsequent uses, you pass NULL. Here is an example that parses a string with three words separated by commas,

int testFunc(String args) {
    char buff[50]; // make this big enough to hold your largest possible input
    args.toCharArray(buff, 50);
    char* first = strtok(buff, ",");
    char* second = strtok(NULL, ",");
    char* third = strtok(NULL, ",");
    Serial.printlnf("first: %s   second: %s   third: %s", first, second, third);
    return 1;
}

Do you have a large number of substrings that you want to separate? What are you doing with each value when you get it? It might be better to use strtok() in a loop if the number is large.

3 Likes