c++的find方法不工作

C++ find method not working

本文关键字:工作 方法 find c++      更新时间:2023-10-16

我对c++很陌生,所以我很抱歉缺乏知识,但是由于某种原因,我的find方法不起作用。任何帮助将是伟大的,这是我正在使用的代码。

www.pastie.org/9434690

//String s21 
string s21 ="| o |";  
if(s21.find("1")){
    cout << "IT WORKS OMG " << s21 << endl;
}
else if(!s21.find("1")){
    cout << "HASOSDKHFSIF" << endl;
}

感谢

忘了说,代码总是打印"IT WORKS",即使字符串中没有"o"。

这里的问题是你的if语句。s21.find("1")将返回要匹配的字符串的字符串中第一个出现的索引。如果没有找到匹配项,则返回string::npos,这是值-1的枚举。If语句将对所有不等于零的数字返回true。因此,您需要像这样对string::npos进行测试:

if(s21.find("1") != std::string::npos)
{
    cout << "IT WORKS OMG " << s21 << endl;
}
else
{
    cout << "HASOSDKHFSIF" << endl;
}

std::string::find 的返回值是找到的子字符串的第一个字符的位置,如果没有找到这样的子字符串,则 std::string::npos 返回值。

您应该使用 std::string::npos 进行字符串匹配

if(s21.find("1") != std::string::npos )
{
    cout << "IT WORKS OMG " << s21 << endl;
}
else 
{
    cout << "HASOSDKHFSIF" << endl;
}

如果你想聪明一点,std::string::npos是二进制中最大的unsigned int,或者1111 1111 1111 1111(人们有时会将str.find()与int -1进行比较,尽管不建议这样做)。您可以通过一些按位操作来利用这个位模式。

翻转所有的位将为除了std::string::npos之外的每个位模式提供非零值,并且由于c++将所有非零值视为true,因此您的if实际上可以是:

if(~s21.find("1"))
{
    cout << "IT WORKS OMG " << s21 << endl;
}
else if(!~s21.find("1"))
{
    cout << "HASOSDKHFSIF" << endl;
}