Sign up ×
Arduino Stack Exchange is a question and answer site for developers of open-source hardware and software that is compatible with Arduino. It's 100% free, no registration required.

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?

share|improve this question

2 Answers 2

up vote 2 down vote accepted

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.

share|improve this answer

Scan function should do the job.

int tv, ar;
char color[10];
sscanf(value, "%d;%d;%s", &tv, &ar, color);
share|improve this answer
    
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
    
@jfpoilpret: corrected, thanks –  TMa Nov 15 '14 at 20:56
    
and where do i tell the sscanf to get val from my var 'value' ? –  Thiago Nov 16 '14 at 9:00
    
@Thiago: as first parameter. Corrected. –  TMa Nov 16 '14 at 11:16

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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