Split string by delimiter strtok weird behaviour

穿精又带淫゛_ 提交于 2020-01-04 04:24:07

问题


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);

回答1:


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 = "|";



回答2:


Change this:

  const char delimeter = '|';

to this:

  const char * delimeter = "|";  // note the double quotes


来源:https://stackoverflow.com/questions/34299875/split-string-by-delimiter-strtok-weird-behaviour

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!