Go Down

Topic: Extracting substring of variable length (Read 1 time) previous topic - next topic


Hi there - the current source string is a String (capital S), the one i should not be using according to PaulS :-(
I'll try to follow what dhenry said, but especially the "search for '+' til the end of the source string;" is something i am not sure about how to do yet.


Ah, so String is based on string.

A String object wraps a NULL terminated char array. That is not quite the same thing as being based on a string.

Typically, when we ask of the OP means string or String, it is because they say one and then post some code that uses the other, or they don't post any/adequate code to make it possible to determine.


The correct way to parse those lines is to parse them!

That means you need to count ',' separators (but ignore them when inside string quotes).  This will get you to the correct
column, and you can extract the string-quote delimited string from there.

Unfortunately proper parsing is often quite complex (string quotes can be escaped inside a string for instance) so
on a tiny little microcontroller its tempting to take shortcuts...  Can come back to bite you later though.
[ I won't respond to messages, use the forum please ]


Dec 13, 2012, 05:31 pm Last Edit: Dec 13, 2012, 06:15 pm by robtillaart Reason: 1
a quick hack to extract with 2 pointers, one to find the start and one to find the end of the string
Code: [Select]

char s[] = "+CMGR: \"REC UNREAD\",\"+8613920001234\",\"\",\"12/12/13,15:08:55+50\""; // note that the \" are escaped with a \\..
char t[20];

void setup()
 int len = strip(s, t);

void loop()

// dedicated function to strip second field which is ... not so elegant ...
int strip(char * in, char * out)
 char *p = in;
 // find start of second field
 while (',' != *p++);
 if (*p =='\"') p++;
 // find endpoint
 char *q = p+1;
 while ('\"' != *q++);  // should also test for end of string ... first ...
 q--;  //we know we have gone 1 byte to far
 int len = q - p;  // warning pointer math
 strncpy(out, p, len);
 return len;
Rob Tillaart

Nederlandse sectie - http://arduino.cc/forum/index.php/board,77.0.html -
(Please do not PM for private consultancy)


Go Up