Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string by delimiter strtok weird behaviour

I am trying to split string ,but unfortunately strtok behaves weirdly

I have following string get|user=password|23|info|hello I have tried widely used method using strtok, but unfortunately it treats = as delimiter and I cannot parse my string. So get parsed correctly than parsed only user, but not user=password.

Please help to find the problem or suggest any other way to split the string. I am programming for Arduino.

Thanks

Code

  const char delimeter = '|';
  char *token;
  token = strtok(requestString, &delimeter);
  // Handle parsed  
  token = strtok(NULL, &delimeter);
like image 757
fwouxicd Avatar asked Feb 28 '26 21:02

fwouxicd


1 Answers

From cppreference,

delim - pointer to the null-terminated byte string identifying delimiters

The requirement that your approach doesn't fit is null terminated. You take the address of a single char, but clearly you cannot access anything past this one symbol. strtok, however, searches for \0 character which terminates the string. Thus you're entering undefined behaviour land.

Instead, use

const char* delimiter = "|";
like image 173
Rostislav Avatar answered Mar 02 '26 10:03

Rostislav



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!