【问题标题】:C++ find method not workingC ++查找方法不起作用
【发布时间】:2014-09-23 17:39:50
【问题描述】:

我对 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”。

【问题讨论】:

  • 查看referencestd::string::find。这一步应该总是在 SO 之前。一个人更快。

标签: c++ string methods find


【解决方案1】:

这里的问题是你的 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;
}

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      如果你想变得更聪明一点,std::string::npos 是二进制中最大的unsigned int1111 1111 1111 1111(人们有时会将 str.find() 与 int -1 进行比较,但不推荐这样做)。您可以通过一点bitwise manipulation 来利用这种位模式。

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-09-21
        • 1970-01-01
        • 2018-10-06
        • 2013-10-15
        • 1970-01-01
        • 1970-01-01
        • 2014-04-26
        • 2021-09-15
        相关资源
        最近更新 更多