为什么string ==字符串比较失败?

时间:2011-06-10 07:53:39

标签: c++ string comparison

以下是我所做的代码片段,在我错误编码的地方可以帮助我:

#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] = '\0'; }
}

int main()
{
    string name("test.rtl");
    string someName("test");
    modifyName(name);

    if( someName == name ) //Failing??
        cout<<"MATCHED"<<endl;
    return 0;
}

3 个答案:

答案 0 :(得分:21)

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

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

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

答案 1 :(得分:13)

它失败了,因为它们不一样..你没有“剪切”字符串,只是更改了字符串。

someNametest,而nametest\0rtlstd::string允许您在内部拥有零字符('\0')< / p>

要剪切字符串,您需要使用std::string::resize或使用std::string::substr自行指定子字符串。我建议resize

答案 2 :(得分:9)

在这一行

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

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

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

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