检查一个string是否包含C ++中的string

我有一个stringtypes的variables。 我想检查它是否包含某个string。 我该怎么做?

有没有一个函数,如果findstring返回true,如果不是,则返回false?

使用std::string::find如下所示:

 if (s1.find(s2) != std::string::npos) { std::cout << "found!" << '\n'; } 

注意:“find了!” 将被打印,如果s2是s1的子string,则s1和s2的types都是std :: string。

你可以尝试使用find函数:

 string str ("There are two needles in this haystack."); string str2 ("needle"); if (str.find(str2) != string::npos) { //.. found. } 

其实,你可以尝试使用boost库,我认为std :: string没有提供足够的方法来做所有常见的string操作。在boost中,你可以使用boost::algorithm::contains

 #include "string" #include "boost/algorithm/string.hpp" using namespace std; using namespace boost; int main(){ string s("gengjiawen"); string t("geng"); bool b = contains(s, t); cout << b << endl; return 0; } 

你可以试试这个

 string s1 = "Hello"; string s2 = "el"; if(strstr(s1.c_str(),s2.c_str())) { cout << " S1 Contains S2"; } 

如果你不想使用标准的库函数,下面是一个解决scheme。

 #include <iostream> #include <string> bool CheckSubstring(std::string firstString, std::string secondString){ if(secondString.size() > firstString.size()) return false; for (int i = 0; i < firstString.size(); i++){ int j = 0; if(firstString[i] == secondString[j]){ while (firstString[i] == secondString[j] && j < secondString.size()){ j++; i++; } if (j == secondString.size()) return true; } } return false; } int main(){ std::string firstString, secondString; std::cout << "Enter first string:"; std::getline(std::cin, firstString); std::cout << "Enter second string:"; std::getline(std::cin, secondString); if(CheckSubstring(firstString, secondString)) std::cout << "Second string is a substring of the frist string.\n"; else std::cout << "Second string is not a substring of the first string.\n"; return 0; } 

这是一个简单的function

 bool find(string line, string sWord) { bool flag = false; int index = 0, i, helper = 0; for (i = 0; i < line.size(); i++) { if (sWord.at(index) == line.at(i)) { if (flag == false) { flag = true; helper = i; } index++; } else { flag = false; index = 0; } if (index == sWord.size()) { break; } } if ((i+1-helper) == index) { return true; } return false; } 
 #include <algorithm> // std::search #include <string> using std::search; using std::count; using std::string; int main() { string mystring = "The needle in the haystack"; string str = "needle"; string::const_iterator it; it = search(mystring.begin(), mystring.end(), str.begin(), str.end()) != mystring.end(); // if string is found... returns iterator to str's first element in mystring // if string is not found... returns iterator to mystring.end() if (it != mystring.end()) // string is found else // not found return 0; }