我有一个std::string类型的变量。我想检查它是否包含一个特定的std::字符串。我该怎么做呢?
是否有一个函数,如果找到字符串返回true,如果没有找到则返回false ?
我有一个std::string类型的变量。我想检查它是否包含一个特定的std::字符串。我该怎么做呢?
是否有一个函数,如果找到字符串返回true,如果没有找到则返回false ?
当前回答
你可以试试这个
string s1 = "Hello";
string s2 = "el";
if(strstr(s1.c_str(),s2.c_str()))
{
cout << " S1 Contains S2";
}
其他回答
使用std::string::find如下所示:
if (s1.find(s2) != std::string::npos) {
std::cout << "found!" << '\n';
}
注意:如果s2是s1的子字符串,则打印"found!", s1和s2都是std::string类型。
还可以使用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";
}
}
使用std::regex_search也不错。让搜索更通用的垫脚石。下面是一个带有注释的例子。
//THE STRING IN WHICH THE SUBSTRING TO BE FOUND.
std::string testString = "Find Something In This Test String";
//THE SUBSTRING TO BE FOUND.
auto pattern{ "In This Test" };
//std::regex_constants::icase - TO IGNORE CASE.
auto rx = std::regex{ pattern,std::regex_constants::icase };
//SEARCH THE STRING.
bool isStrExists = std::regex_search(testString, rx);
需要包含#include <regex>
出于某种原因,假设输入字符串被观察到类似于“在这个示例字符串中查找一些东西”,并且有兴趣搜索“在这个测试中”或“在这个示例中”,那么可以通过简单地调整如下所示的模式来增强搜索。
//THE SUBSTRING TO BE FOUND.
auto pattern{ "In This (Test|Example)" };
从这个网站上的这么多答案中,我没有找到一个明确的答案,所以在5-10分钟内我自己找到了答案。 但这可以在两种情况下实现:
要么你知道你在字符串中搜索的子字符串的位置 要么你不知道它的位置,然后逐字符搜索它……
所以,让我们假设我们在字符串“abcde”中搜索子字符串“cd”,我们使用c++中最简单的substr内置函数
1:
#include <iostream>
#include <string>
using namespace std;
int i;
int main()
{
string a = "abcde";
string b = a.substr(2,2); // 2 will be c. Why? because we start counting from 0 in a string, not from 1.
cout << "substring of a is: " << b << endl;
return 0;
}
2:
#include <iostream>
#include <string>
using namespace std;
int i;
int main()
{
string a = "abcde";
for (i=0;i<a.length(); i++)
{
if (a.substr(i,2) == "cd")
{
cout << "substring of a is: " << a.substr(i,2) << endl; // i will iterate from 0 to 5 and will display the substring only when the condition is fullfilled
}
}
return 0;
}
#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;
}