gpt4 book ai didi

c++ - 在 C++ 中检查另一个字符串中的字符串

转载 作者:行者123 更新时间:2023-11-30 03:53:56 24 4
gpt4 key购买 nike

#include <iostream>
#include <string>
using namespace std;

int main() {
string str_1 = "Gandalf";
string str_2 = "dal";
for (int i = 0; i <= str_1.length() - 2; i++)
for (int j = 0; j <= str_2.length(); j++) {
if (str_2[j] == str_1[i]) {
if (str_2[j + 1] == str_1[i + 1]) {
if (str_2[j + 2] == str_1[i + 2])
cout << "true";
}
}
}
return 0;
}

我可以做到,但是如果 str_2 的长度是 4 个字符,程序将无法运行。我希望该程序适用于每个长度的字符串但是如何呢?

最佳答案

下面的函数 find 基本上重现了 std::string::find 的行为(没有起始位置参数)。你需要:

  • 遍历外部字符串,并在每一步:
  • 循环检查每个字符的第二个字符串。
  • 如果其中任何一个失败,则返回到外循环。
  • 如果我们一直通过内循环,那么第二个字符串就在那里,并返回外循环中的当前位置。
  • 如果我们在第一个字符串中用完了空间,就跳过其余部分。

希望评论能说明这一点。我还包括一个小的实用函数来将找到的位置转换为 true/false,以及一些测试。

#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
}

这比您真正需要的要多,但它最接近“真实”答案的模型(使用语言提供的工具)。此外,它不是一个很好的家庭作业答案,但包含编写家庭作业答案的所有线索。

关于c++ - 在 C++ 中检查另一个字符串中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29858348/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com