检查字符串是否包含另一串字符串(c++)

在c++中检查字符串是否包含另一串字符串,这个本来是我做过的一个算法题,不过最近刚好有个需求让我想到了这个题,就在此记录一下!

  1. 使用std::string::findfunction
string str ("There are two needles in this haystack."); string str2 ("needle"); if (str.find(str2) != string::npos) { //.. found. //如果不等,则说明找到一样的,如果相等,则说明没找到,可以查看find的具体用法:http://www.cplusplus.com/reference/string/string/find/ }
  1. 自己编写程序
#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; }
  1. 使用boost库,在boost中,你可以只使用boost::algorithm::contains:
#include "string" #include "boost/algorithm/string.hpp" using namespace std; using namespace boost; int main(){ string s("Hello Word!"); string t("ello"); bool b = contains(s, t); cout << b << endl; return 0; }

如果您有更好的算法或者方法请私信或者评论我!


__EOF__

本文作者stone
本文链接https://www.cnblogs.com/qscgy/p/13358130.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   zko  阅读(2866)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示