Can anyone explain how things like strtok() and strstr() can be used to provide a numeric value for a substring location position within the mainstring array.
I've tried to understand from the C++ examples, but their 'position' locations of the substring within the mainstring (which I need) are returned in C++ as %d variables, whereas all I can get returned by the arduino 'char * pointer=' is the actual substring chars if they exist, rather than a number for their start position locations within the mainstring.
The C++ examples show that it is possible to discover the position values from %d, but how can I get that equivalent position value in arduino?
I want to be able to parse a char header[30] array for occurances of things like "s=123" and "d=789" in order to extract and assign the specified values to any appropriate variables (source or destination etc).
1 Answer 1
You have to define a format for the header you will be parsing and stick to that format. Say this is a sample header
terminated by null:
s=123 d=789 e=463
A common property of each assignment in the string is the '=' symbol. You can use that to locate each variable and the value assigned to it. strchr
is the function to use to locate a single character. Once you locate the = character, you move back and then forward along the array to obtain the variable and its value.
I will make some assumptions here: that your variable names will be single character, that numbers assigned will be no bigger than ints, and a space character is used to separate assignments.
char header[] = "s=123 d=789 e=463";
int d, s, e; //your variables to be assigned to
char * ptr = header;
char * eq = NULL; //locate assmts
int * num = NULL; //just for starters
while (1){
eq = strchr(ptr, '=');
ptr = eq; // update the pointer
if (ptr == NULL) // found no = chars
break;
switch (*(ptr - 1)){
case 'd': //all the possible variables
num = &d; break;
case 's':
num = &s; break;
case 'e':
num = &e; break;
default: //unknown variable
num = NULL;
}
ptr++;
if (num == NULL) //unrecognized var
continue; // locate next = char
*num = 0;
while (*ptr && (*ptr != ' ')){ // while space or end of string not yet reached
*num *= 10; // extract each int
*num += *ptr - '0';
ptr++;
}
}
Serial.println(d); //now contains the numbers in the header
Serial.println(s);
Serial.println(e);
Untested but it should work for the header sample I gave.
-
Your answer is excellent Mr T, thank you very much indeed.Electroguard– Electroguard2016年03月04日 16:51:15 +00:00Commented Mar 4, 2016 at 16:51
-
@Electroguard You're welcome. I've seen your other question. You may have to get rid of
strchr
in the receiver code and do the searching yourself, if you want to implement checksums efficiently.SoreDakeNoKoto– SoreDakeNoKoto2016年03月06日 01:33:35 +00:00Commented Mar 6, 2016 at 1:33
sscanf()
is way more appropriate for what you want to do than anystr*()
functions.