通过分隔符 strtok 奇怪的行为拆分字符串 [英] Split string by delimiter strtok weird behaviour

查看:37
本文介绍了通过分隔符 strtok 奇怪的行为拆分字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试拆分字符串,但不幸的是 strtok 表现得很奇怪

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

我有以下字符串 get|user=password|23|info|hello 我尝试过使用 strtok 广泛使用的方法,但不幸的是它把 = 视为分隔符,我无法解析我的字符串.所以 get 比只解析 user 而不是 user=password 解析正确.

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.

请帮助查找问题或提出任何其他拆分字符串的方法.我正在为 Arduino 编程.

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

谢谢

代码

  const char delimeter = '|';
  char *token;
  token = strtok(requestString, &delimeter);
  // Handle parsed  
  token = strtok(NULL, &delimeter);

推荐答案

来自 cppreference,

delim - 指向以 null 结尾的字节字符串标识分隔符的指针

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

您的方法不适合的要求是空终止.您获取单个 char 的地址,但显然您无法访问超过这个符号的任何内容.然而,strtok 会搜索终止字符串的 \0 字符.因此,您正在进入未定义行为领域.

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.

改为使用

const char* delimiter = "|";

这篇关于通过分隔符 strtok 奇怪的行为拆分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆