我有一个std::string类型的变量。我想检查它是否包含一个特定的std::字符串。我该怎么做呢?
是否有一个函数,如果找到字符串返回true,如果没有找到则返回false ?
我有一个std::string类型的变量。我想检查它是否包含一个特定的std::字符串。我该怎么做呢?
是否有一个函数,如果找到字符串返回true,如果没有找到则返回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;
}
其他回答
如果字符串的大小相对较大(数百字节或更多),并且c++17可用,您可能需要使用Boyer-Moore-Horspool搜索器(示例来自cppreference.com):
#include <iostream>
#include <string>
#include <algorithm>
#include <functional>
int main()
{
std::string in = "Lorem ipsum dolor sit amet, consectetur adipiscing elit,"
" sed do eiusmod tempor incididunt ut labore et dolore magna aliqua";
std::string needle = "pisci";
auto it = std::search(in.begin(), in.end(),
std::boyer_moore_searcher(
needle.begin(), needle.end()));
if(it != in.end())
std::cout << "The string " << needle << " found at offset "
<< it - in.begin() << '\n';
else
std::cout << "The string " << needle << " not found\n";
}
使用std::string::find如下所示:
if (s1.find(s2) != std::string::npos) {
std::cout << "found!" << '\n';
}
注意:如果s2是s1的子字符串,则打印"found!", s1和s2都是std::string类型。
你可以尝试使用find函数:
string str ("There are two needles in this haystack.");
string str2 ("needle");
if (str.find(str2) != string::npos) {
//.. found.
}
还可以使用System命名空间。 然后可以使用contains方法。
#include <iostream>
using namespace System;
int main(){
String ^ wholeString = "My name is Malindu";
if(wholeString->ToLower()->Contains("malindu")){
std::cout<<"Found";
}
else{
std::cout<<"Not Found";
}
}
实际上,你可以尝试使用boost库,我认为std::string没有提供足够的方法来做所有常见的字符串操作。在boost中,你可以只使用boost::algorithm::包含:
#include <string>
#include <boost/algorithm/string.hpp>
int main() {
std::string s("gengjiawen");
std::string t("geng");
bool b = boost::algorithm::contains(s, t);
std::cout << b << std::endl;
return 0;
}