字符串==字符串比较失败的原因
Why string==string comparison failing?
以下是我所做的代码片段,在我错误编码的地方,有人能帮我吗:
#include<iostream>
using namespace std;
void modifyName(string &name)
{
size_t sep = string::npos;
sep = name.find_first_of(".");
if(sep != string::npos) { name[sep] = ' '; }
}
int main()
{
string name("test.rtl");
string someName("test");
modifyName(name);
if( someName == name ) //Failing??
cout<<"MATCHED"<<endl;
return 0;
}
正如其他人所说,字符串不匹配,因为一个是"test rtl"
,另一个是"test"
。使用==
进行std::string
比较是很好的,因为运算符是为字符串相等而重载的。要做你想做的事,你应该尝试更换
if(sep != string::npos) { name[sep] = ' '; }
带有
if(sep != string::npos) { name.resize(sep); }
它失败了,因为它们不一样。。你没有"剪切"字符串,只是更改了其中的一个字符。
someName
是test
,而name
是test rtl
(std::string
允许你在里面有零个字符(' '
))
要剪切字符串,需要使用std::string::resize
或使用std::string::substr
自分配子字符串。我推荐resize
。
在行中
if(sep != string::npos) { name[sep] = ' '; }
您正在将字符串修改为"test rtl"
。std::basic_string可以包含null字符,因此字符串不相同。您可以使用substr
来截断字符串:
if(sep != string::npos) { name = name.substr(sep); }
这将导致字符串变为"test"
,应该(!!)进行正确比较。
相关文章:
- 使用提升对字符串进行标记化时,将令牌转换为 char* const* 时失败
- std::p作为 std 中定义的unordered_map自定义键的字符串的空气失败并出现模板错误
- C++ TCP 服务器比较字符串失败
- 嵌套列表(字符串向量的向量)初始化失败
- C++长到字符串的转换失败
- 字符串流运算符输入失败
- AES/CFB密码模式从字符串失败中解密
- 增强精神解析报价字符串失败
- BOOST :: lexical_cast to std ::字符串失败
- 假定相同的字符串之间的比较失败' == '比较
- 如何在类中存储指向字符串到成员函数映射的智能指针,以便它不会因类型不完整而失败?
- 从文件中提取的数据中的C 搜索字符串失败
- C++:为什么这个字符串输入失败,而另一个没有
- 失败的证明转换字符串到枚举类
- 当Find_first_not_of击中字符串末尾时,为什么会失败
- C++ 使用字符串时运行失败
- 在字符串上循环以查看字符串失败的位置
- 当显式调用非默认函数时,覆盖自定义字符串失败
- DCOM中的SAFEARRAY(BSTR) as [out]参数返回字符串失败
- 从函数返回本地var字符串失败,而本地var int和char工作正常.为什么