I want to split this:
char* value = "12;32;blue";
or
string value = "12;32;blue";
into this vars:
TV = 12;
AR = 32;
LED = "blue";
is it possible?
2 Answers 2
For C-strings (char*
), your best option (in terms of performance and memory consumption) is to use strtok
:
char* value = "12;32;blue";
char* token = strtok(value, ";");
int TV = atoi(token);
token= strtok(0, ";");
int AR = atoi(token);
token = strtok(0, ";");
char* LED = token;
Note 1: the code above takes it for granted that value
is properly formatted, i.e. contains 3 parts split by ;
. If it is not sure, then you should add additional checks on token
value returned by strtok
.
Note 2: strtok
is modifiying its value
argument, so that at the end of the code above, value
will not be equal to 12;32;blue
any longer.
Note 3: LED
variable above will point directly to the character b
inside value
, which means that if value
is modified afterwards, LED
might be modified as well.
Scan function should do the job.
int tv, ar;
char color[10];
sscanf(value, "%d;%d;%s", &tv, &ar, color);
-
That's a great old trick. I totally forgot about it! daniweb.com/software-development/c/code/216535/…Jasmine– Jasmine2014年11月14日 17:09:47 +00:00Commented Nov 14, 2014 at 17:09
-
I think you meant
sscanf
notscanf
as the latter needsstdin
which Arduino doesn't have. Also in your example you shouldn't pass&color
, but rathercolor
.jfpoilpret– jfpoilpret2014年11月15日 09:33:25 +00:00Commented Nov 15, 2014 at 9:33 -
and where do i tell the sscanf to get val from my var 'value' ?Lugarini– Lugarini2014年11月16日 09:00:55 +00:00Commented Nov 16, 2014 at 9:00
-
@Thiago: as first parameter. Corrected.TMa– TMa2014年11月16日 11:16:08 +00:00Commented Nov 16, 2014 at 11:16