string str ("There are two needles in this haystack.");
string str2 ("needle");
if (str.find(str2) != string::npos) {
//.. found.
}
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;
}
#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;
}
for 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;
}
-2
如果您不想使用标准库函数,下面是一个解决方案 .
#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 the first characters match
if(firstString[i] == secondString[j]){
int k = i;
while (firstString[i] == secondString[j] && j < secondString.size()){
j++;
i++;
}
if (j == secondString.size())
return true;
else // Re-initialize i to its original value
i = k;
}
}
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;
}
8 回答
你可以试试这个
实际上,你可以尝试使用boost库,我认为std :: string没有提供足够的方法来完成所有常见的字符串操作 . 在boost中,你可以只使用boost::algorithm::contains:
这是一个简单的功能
使用std::string::find如下:
注意:如果
s2
是s1
的子字符串,则将打印"found!",s1
和s2
的类型均为std::string
.您可以尝试使用find函数:
从这个网站上的这么多答案我没有找到一个明确的答案所以在5-10分钟内我自己找到了答案 . 但这可以在两种情况下完成:
要么 KNOW 您在字符串中搜索的子字符串的位置
要么你 don't know 位置并搜索它,char by char ...
所以,我们假设我们在字符串"abcde"中搜索子字符串"cd",并且我们在C中使用最简单的substr内置函数
for 1:
for 2:
如果您不想使用标准库函数,下面是一个解决方案 .