0

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?

asked Nov 14, 2014 at 5:55

2 Answers 2

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.

answered Nov 14, 2014 at 7:45
3

Scan function should do the job.

int tv, ar;
char color[10];
sscanf(value, "%d;%d;%s", &tv, &ar, color);
answered Nov 14, 2014 at 7:34
4
  • That's a great old trick. I totally forgot about it! daniweb.com/software-development/c/code/216535/… Commented Nov 14, 2014 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. Commented Nov 15, 2014 at 9:33
  • and where do i tell the sscanf to get val from my var 'value' ? Commented Nov 16, 2014 at 9:00
  • @Thiago: as first parameter. Corrected. Commented Nov 16, 2014 at 11:16

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.