Split string into 2 strings by delimiter

I'm trying to split a 2 word string into 2 separate strings, but it doesn't work. second_word just becomes null pointer. Why's that?

void execute_command(char* command) {
    char *first_word;
    char *second_word;
    
    first_word = strtok(command, " ");
    second_word = strtok(NULL, " ");
    
    Serial.println(first_word);
    Serial.println(second_word);
}

What exactly is the format of command ?

any 2 words. Like "set 2" or "reset 1".

Show how you call this function

This works for me

void setup()
{
  Serial.begin(115200);
  execute_command("set 1");
}

void loop()
{
}

void execute_command(char* command)
{
  char *first_word;
  char *second_word;
  first_word = strtok(command, " ");
  second_word = strtok(NULL, " ");
  Serial.println(first_word);
  Serial.println(second_word);
}

Output

set
1

In some cases, this will not work :

execute_command("set 1");

Because the string may be compiled as a constant, thus cannot be modifed by strtok

This will always work :

char cmd[] = "set 1";
execute_command(cmd);

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