I want to split this:

char* value = "12;32;blue";
string value = "12;32;blue";

into this vars:

TV = 12;
AR = 32;
LED = "blue";

is it possible?


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
    Nov 14 '14 at 17:09
  • I think you meant sscanf not scanf as the latter needs stdin which Arduino doesn't have. Also in your example you shouldn't pass &color, but rather color.
    – jfpoilpret
    Nov 15 '14 at 9:33
  • and where do i tell the sscanf to get val from my var 'value' ?
    – Lugarini
    Nov 16 '14 at 9:00
  • @Thiago: as first parameter. Corrected.
    – TMa
    Nov 16 '14 at 11:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.