Cut char with separator not working

Hello,

I'm currently trying to cut a char into several pieces of text.

void setup() {

  Serial.begin(115200);

  char data[] = "test,ca,va?,,test";

    char sep[] = ",";

 

  String *liste;

  liste = cutString(data,sep);

Serial.println(liste[0]);

 

}

 

String * cutString(char data[],char sep[]){

  Serial.begin(115200);

  int number = 0;

int size = String(data).length();

 

  for (int i = 0; i < size; i++){

    if(data[i]==sep[0]){

      number ++;

    }

  }

String * list;

char *d = strtok(data, ",");

list[0]=String(d);

int i =1;

while (d != NULL) {

       d = strtok(NULL, ",");

       list[i] = String(d);

       i++;

   }

 



 

return list;

}

 

void loop() {

  // put your main code here, to run repeatedly:

 

}

There is my code.

Everything works fine in the cutString function (when i do serial print, I retrieve what I want), but when called, I think there is something wrong, as nothing appears in serial monitor, and no build issue.

Can you help me please ?

Thanks you a lot !

I'm compiling for nodemcu 0.9 esp8266

String * list;
...

list[0]=String(d);


  

Oops.

Crazy mix of Strings and strings.
Why?
Why initialize the serial device more than once?I

Not really an installation issue, is it?

@mistano, your topic has been moved to a more suitable location on the forum. Installation and Troubleshooting is not for problems with (nor for advise on) your project :wink: See About the Installation & Troubleshooting category.

I tried to do some things to debug my code, but I didn't removed these modifications. At the begining, I wanted to have a function taking a char input, a char separator, to return a list of all separated characters.

I agree with you that I did crazy things here, but I was very lost with all of that. Can you help me do it the good way please ?

Hello,

Thank you a lot for that, I will go to check that

consider

#define MAX_TOK   10
char **
cutString (
    const char *str,
    const char *sep )
{
    static char *tok [MAX_TOK];
    char  s[80];

    strcpy (s, str);

    tok [0] = strtok (s, sep);
    for (int n = 1; n < MAX_TOK && NULL != (tok [n] = strtok (NULL, sep)); n++)
        ;

    return tok;
}

void setup () {
    Serial.begin (9600);

    char **p = cutString ("test,ca,va?,,test", ",");

    while (*p)
        Serial.println (*p++);
}

void loop () {
}

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.