【问题标题】:Why string::find() is not working in this code?为什么 string::find() 在此代码中不起作用?
【发布时间】:2019-01-11 06:32:36
【问题描述】:

我有一个 std::string 类型的变量。我想检查它是否包含某个 std::string。我该怎么做?

#include<bits/stdc++.h>
using namespace std;

 int main()
 {
     int n;
     string str;
     cin >> n;
    string str1 = "not";
    while(n--)
   {
     cin >> str;
       cout << "2";
    if(str.size() >= str1.size())
    {
      if (str.find(str1) != string::npos) 
      {
        cout << "1";
      } 
     else
        cout << "2";
    }   

  }
    return 0;
}

输入:

      2
      i do not have any fancy quotes
      when nothing goes right go left

输出:无输出

【问题讨论】:

标签: string find c++14


【解决方案1】:

从输入流中读取一个整数后,您应该在从输入流中读取任何字符串之前使用cin.ignore();

cin.ignore(); 忽略“换行”字符。

此外,您无法读取包含@​​987654323@ 的一些空格的行。您应该使用getline(cin, str); 来读取一行。

您修改后的代码:

#include<bits/stdc++.h>
using namespace std;

int main() {
  int n;
  string str;
  cin >> n;
  cin.ignore();
  string str1 = "not";
  while (n--) {
    getline(cin, str);
    if (str.find(str1) != string::npos) 
      cout << "YES" << endl;
    else
      cout << "NO" << endl;
  }
  return 0;
}

输入:

7
a
bbbbbbbbbb
not bad
not good
not not not not
NOT
aaaaaanotbbb

输出:

NO
NO
YES
YES
YES
NO
YES

【讨论】:

    猜你喜欢
    • 2013-01-10
    • 1970-01-01
    • 1970-01-01
    • 2011-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多