You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何string.find_first_of表现异常?汇编解析器字符串截取问题

问题分析与解决

问题描述

开发汇编解析器时,通过指引字符串切割文本获取令牌,代码如下:

string s = "$t4,";
string guide = "$!,$!,$!";
int i = 1;
string test =s.substr(0, s.find_first_of(" ,.\t"+to_string(guide[i+1]) ));
cout <<  test << "\n";

当s为"$t4"时,test结果为"$t",预期应为"$t4";其他$tX形式字符串(X≠4)均正常,且4不在预期的匹配字符集中。

问题根源

问题出在to_string(guide[i+1])的使用逻辑:

  • 当i=1时,guide[i+1]对应guide[2],字符为','(ASCII码值为44)。
  • to_string函数处理char类型参数时,会将其视为整数(ASCII值)转换为字符串,因此to_string(',')得到的是"44",而非预期的","。
  • 最终find_first_of的匹配字符集变为" ,.\t44",包含了字符'4',导致s="$t4"中的'4'被误判为分隔符,提前完成切割。

解决方案

将to_string(guide[i+1])替换为string(1, guide[i+1]),直接将单个字符构造成目标字符串,避免ASCII码转换的干扰:

string s = "$t4,";
string guide = "$!,$!,$!";
int i = 1;
// 用string(1, char)构造单个字符的字符串,确保匹配集仅包含目标分隔符
string test = s.substr(0, s.find_first_of(" ,.\t" + string(1, guide[i+1])));
cout << test << "\n";

修改后匹配字符集仅包含",",不会引入'4',即可正确获取"$t4"作为结果。

内容的提问来源于stack exchange,提问作者Different

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 20:51:20