将字符串分割符由strtok的怪异的行为 [英] Split string by delimiter strtok weird behaviour
问题描述
我想分裂字符串,但不幸的是 strtok的
的行为方式古怪
我有以下字符串获取|用户=密码| 23 |资讯|打招呼
我曾尝试使用strtok的广泛使用的方法,但不幸的是它把 =
作为分隔符,我无法解析我的字符串。
因此, GET
正确地分析比分析只用户
,而不是用户=密码
。
请帮助查找问题或建议其他任何方式来分割字符串。
我编程的Arduino的。
感谢
code
为const char分隔符=|;
字符*记号。
令牌= strtok的(requestString,&安培;分隔符);
//处理解析
令牌= strtok的(NULL,&安培;分隔符);
从的 CP preference ,
DELIM - 指向空终止字节的字符串分隔符标识
块引用>这是你的做法不符合要求的空终止的。你把一个
字符
的地址,但显然你不能访问任何过去,这一个符号。strtok的
,然而,对于\\其终止字符串0
字符搜索。因此,你正在进入未定义行为的土地。相反,使用
为const char *分隔符=|;
I am trying to split string ,but unfortunately
strtok
behaves weirdlyI 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. Soget
parsed correctly than parsed onlyuser
, but notuser=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);
解决方案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 = "|";
这篇关于将字符串分割符由strtok的怪异的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!