字符串==字符串比较失败的原因

Why string==string comparison failing?

本文关键字:字符串 失败 比较      更新时间:2023-10-16

以下是我所做的代码片段,在我错误编码的地方,有人能帮我吗:

#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;
}

正如其他人所说,字符串不匹配,因为一个是"testrtl",另一个是"test"。使用==进行std::string比较是很好的,因为运算符是为字符串相等而重载的。要做你想做的事,你应该尝试更换

if(sep != string::npos) { name[sep] = ''; }

带有

if(sep != string::npos) { name.resize(sep); }

它失败了,因为它们不一样。。你没有"剪切"字符串,只是更改了其中的一个字符。

someNametest,而nametestrtlstd::string允许你在里面有零个字符(''))

要剪切字符串,需要使用std::string::resize或使用std::string::substr自分配子字符串。我推荐resize

在行中

if(sep != string::npos) { name[sep] = ''; }

您正在将字符串修改为"testrtl"。std::basic_string可以包含null字符,因此字符串不相同。您可以使用substr来截断字符串:

if(sep != string::npos) { name = name.substr(sep); }

这将导致字符串变为"test",应该(!!)进行正确比较。