检查字符串是否相同 C++

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16696559/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 20:32:54  来源:igfitidea点击:

Checking if strings are the same c++

c++stringcompare

提问by Michael Kimin Choo

For my case, I have to check if 2 strings are the same. The probelm I'm getting, is that No matter what I input, I'm getting a true value regardless of what I put in.

就我而言,我必须检查 2 个字符串是否相同。我得到的问题是,无论我输入什么,无论我输入什么,我都会得到一个真正的价值。

bool Dictionary::checkIfWordExists(string input){
for(int counter=0;counter<234;counter++){
    if(input.compare(getWordFromDictionary(counter))){
        return true;
    }
}
return false;}

For testing purposes I used a do loop like this to type in stuff to test in comparison to the dictionary.txt file that I loaded.

出于测试目的,我使用了这样的 do 循环来输入要测试的内容,与我加载的 dictionary.txt 文件进行比较。

do{
    cout<<"enter something you sexy beast"<<endl;
    string test;
    cin>>test;
    if(loadedDictionary.checkIfWordExists(test)){
        cout<<"yes"<<endl;
    }else{
        cout<<"no"<<endl;
    }
}while(true);

回答by Overv

That's because compare actually returns 0when the strings are equal. If the strings are not equal, it will return a value higher or lower and the if will evaluate to true, as you are seeing.

那是因为0当字符串相等时compare 实际上返回。如果字符串不相等,它将返回一个更高或更低的值,并且 if 将评估为 true,如您所见。

It is common in languages like Java and C# to use methods like equalsto compare non-primitives, but in C++ it is preferably to just use ==.

在 Java 和 C# 等语言中,使用equals比较非原语等方法是很常见的,但在 C++ 中,最好只使用==.

回答by andre

There should be an operator==for std::stringavailable for a more natural feeling comparison.

应该有一个operator==forstd::string可用于更自然的感觉比较。

if(input == getWordFromDictionary(counter)) { ... }

回答by yasouser

You need to explicitly compare the result of comparewith 0. Here is what the return values mean:

您需要明确比较comparewith的结果0。以下是返回值的含义:

0 => The compared strings are equal

0 => 比较的字符串相等

<0 => Either the value of the first character that does not match is lower in the compared string, or all compared characters match but the compared string is shorter.

<0 => 要么是比较字符串中第一个不匹配的字符的值较小,要么所有比较字符都匹配但比较字符串较短。

>0 => Either the value of the first character that does not match is greater in the compared string, or all compared characters match but the compared string is longer.

>0 => 要么比较字符串中第一个不匹配的字符的值越大,要么所有比较字符都匹配但比较字符串较长。

See here for the detailed explanation on std::string::compare.

有关std::string::compare的详细说明,请参见此处。