Hi all, thanks for the suggestions.
I am experimenting with this strtok. (or strtok_r, but this indeed gives protest in compiling...?).
Using this example below as a starting point.
The example works...but I really don't understand what is happening. You put something in the setup, and thanks to the stuff in the main-loop you get the right results?? I am missing this concept. I thought that a setup runs first and initiates the data for the next part. But this contradicts that concept.
The use of the asterisk is also intriguing, like in *record1. I am looking for some info/theory about this because this is new to me.
I tried several ways to put everything inside the void loop and create a function, but did not manage to do it.
Also, in my situation my strings are of different length, but I can easily put separators or delimiters in the incoming message if necessary. By example an incoming string like: 255^133^24^150^!
But how to use this strtok?
tnx...
/* strtok teststrtok test
output:
Split record1:
one
two
three
Split record2:
Hello
there
friend
*/
#include <string.h>
#define MAX_STRING_LEN 20
char *record1 = "one two three";
char *record2 = "Hello there friend";
char *p, *i;
void setup() {
Serial.begin(9600);
Serial.println("loaded file test_strtok_10.ino");
Serial.println("");
Serial.println("Split record1: ");
Serial.println(subStr(record1, " ", 1));
Serial.println(subStr(record1, " ", 2));
Serial.println(subStr(record1, " ", 3));
Serial.println("Split record2: ");
Serial.println(subStr(record2, " ", 1));
Serial.println(subStr(record2, " ", 2));
Serial.println(subStr(record2, " ", 3));
}
void loop () {
}
// Function to return a substring defined by a delimiter at an index
char* subStr (char* str, char *delim, int index) {
char *act, *sub, *ptr;
static char copy[MAX_STRING_LEN];
int i;
// Since strtok consumes the first arg, make a copy
strcpy(copy, str);
for (i = 1, act = copy; i <= index; i++, act = NULL) {
//Serial.print(".");
sub = strtok_r(act, delim, &ptr);
if (sub == NULL) break;
}
return sub;
}