下面的函数find
基本上重现了std::string::find
(没有起始位置参数)的行为。通过外串
- 循环,然后在每一步:您需要
- 遍历第二个字符串检查每个字符。
- 如果其中任何一个失败,请回退到外部循环。
- 如果我们完成整个内部循环,那么第二个字符串就在那里,并返回外部循环中的当前位置。
- 如果我们在第一个字符串中空间不足,请跳过其余部分。
希望评论能够说明这一点。我还包括一个小的实用功能,将找到的位置变成真/假,以及一些测试。
#include <iomanip>
#include <iostream>
#include <string>
std::string::size_type find(const std::string& s1,
const std::string& s2)
// return the position of s2 within s1,
// else npos if it is not present.
{
using size_type = std::string::size_type;
size_type curPos = 0;
size_type lim = s1.size();
size_type innerLim = s2.size();
for (; curPos<lim; ++curPos) { // loop through s1
if (lim < curPos+innerLim) {
break; // not enough space left
}
size_type innerPos = 0;
for(; innerPos < innerLim // loop through s2, while matching
&& curPos + innerPos < lim
&& s1[innerPos+curPos] == s2[innerPos];
++innerPos) ; // do nothing in the loop
if (innerPos == innerLim) { // matched the whole loop
return curPos;
}
}
return std::string::npos; // never matched
}
bool contains(const std::string& s1,
const std::string& s2)
{
return find(s1, s2)!=std::string::npos;
}
int main()
{
std::cout
<< std::boolalpha
<< contains("abc", "") << '\n' // true
<< contains("abc", "abc") << '\n' // true
<< contains("abc", "bc") << '\n' // true
<< contains("abc", "abcd") << '\n' // false
<< contains("abc", "abd") << '\n' // false
<< contains("abc", "xyz") << '\n';// false
}
这不仅仅是你真正需要的东西,而是它最接近地模拟了“真实”的答案(使用语言提供的设施)。此外,它使它不是一个伟大的家庭作业答案,但包含写作业答案的所有线索。
你想检查'str_1'是否包含'str_2'? ['return str_1.find(str_2)!= std :: string :: npos;'](http://en.cppreference.com/w/cpp/string/basic_string/find) – BoBTFish
是的,str_1总是长于ste_2 –
我不得不使用find() –