Hi!
I'm trying to split a string at a comma this is my string: Sunday, July 10 2022 10:17:27
and this is what I'm trying to get: July 10 2022 10:17:27
I've tried to use strtok(), but the output is: Sunday
So you probably only used strtok() once in your code. the example on https://cplusplus.com/reference/cstring/strtok/ shows how it can be used to split the full string. Note the use of the while-loop.
If you still have problems after that, post your code.
Note:
The example is not tailored to Arduino.
Like this:
char array[] = "Sunday, July 10 2022 10:17:27";
char *strings[3]; // an array of pointers to the pieces of the above array after strtok()
char *ptr = NULL;
void setup()
{
Serial.begin(9600);
//Serial.print(array);
byte index = 0;
ptr = strtok(array, " ,"); // delimiters space and comma
while (ptr != NULL)
{
strings[index] = ptr;
index++;
ptr = strtok(NULL, ",");
}
//Serial.println(index);
// print all the parts
Serial.println("The Pieces separated by strtok()");
for (int n = 0; n < index; n++)
{
Serial.print("piece ");
Serial.print(n);
Serial.print(" = ");
Serial.println(strings[n]);
}
}
void loop()
{
// step away, nothing to see here.
}
Output:
The Pieces separated by strtok()
piece 0 = Sunday
piece 1 = July 10 2022 10:17:27
subsequent calls to strtok () are passed a NULL pointer. strtok() captures a ptr to the string passed to it processes it during these subsequent calls
This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.