Finding a location of multiple comma's in a string

Hi Guys;
Is there a way to locate the position of the 6th 7th & 8th comma in a string.

the string will be something like:

Cars,3,87,Blue,FWD,4 Door,Radio,Sunroof,Hatchback,15,95,1528

I am trying to pull the data for the location of Radio & Sunroof

from there I can pull the data between those locations.

Rick

strtok() is convenient.

I will try that out.

Thanks, Rick

I cant get anything past the first comma, what am I doing wrong?

Rick


void setup(){
  Serial.begin(9600);
}
char a[]="Cars,3,87,Blue,FWD,4 Door,Radio,Sunroof,Hatchback,15,95,1528";

void loop(){
char *token;

token = strtok(a,",");
if (token == NULL){
  Serial.println("empty");
}
  Serial.println(token);
  token = strtok(NULL, ",");
}

You need to study the example more closely.

In your code every call to loop() starts all over from the beginning of the character string a. So you get only the first token every time.

This works as expected:

void setup(){
  Serial.begin(115200);

char a[]="Cars,3,87,Blue,FWD,4 Door,Radio,Sunroof,Hatchback,15,95,1528";
char* token = strtok(a,",");
  while (token != NULL)
  {
    Serial.println(token);
    token = strtok (NULL, ",");
  }
}
void loop(){}

Hi jremington,

I just get a blank screen!

Rick

Did you set the Baud rate correctly on the serial monitor?

yes

it works for me

Here is what I get on an Uno, (Baud rate 115200):
Cars
3
87
Blue
FWD
4 Door
Radio
Sunroof
Hatchback
15
95
1528

I am using the MICRO, I have tried 115200 and 9600.

no data...

Post the code, using code tags.

you have use Serial1 for USB on Micro

its your code exactly

Rick

serial1 is a blank screen too

I think you experiencing a problem with Serial, not with strtok code.
Add a line that print something to Serial just after Serial.begin()

You might try waiting for the USB connection to be established, something like

Serial.begin(115200);
while(!Serial); //wait for connection
Serial.println("starting");

I don't have a Micro to to test.

1 Like

THAT DID IT!!!

Thanks

Rick

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.