c++ - 如何判断一个字符串是否包含另一个字符串

标签 c++ stl

我有一组字符串,然后是第二组字符串。我想遍历该集合并确定当前字符串是否包含在第二个字符串中。 STL 或其中的任何工具是否有任何工具可以让我轻松工作?

#include <cctype>
#include <iostream>
#include <iomanip>
#include <set>
#include <list>
#include <map>
#include <vector>
#include <queue>
#include <string>

用例:

test1 . Add    ( 0, "hello" );
test1 . Add    ( 1, "world" );
test1 . Add    ( 2, "rld" );
test1 . Add    ( 3, "ell" );
test1 . Add    ( 4, "hell" );
printSet ( test1 . Search ( "hello world!" ) );
// 0, 1, 2, 3, 4
printSet ( test1 . Search ( "hEllo world!" ) );
// 1, 2

当然,我可以逐个字符串、逐个字符地比较它,或者创建一些自动机,但为什么要让事情变得比实际更难 :)

最佳答案

您可以使用 std::string::find用于搜索,boost::bind 将其传递到 std::for_each 并使用 boost::lambda 将结果与 std 进行比较::string::npos 并计算它们
您可以找到相关示例 Here
另一种更直接的方法是创建自己的仿函数,它将在构造函数中接受字符串,在 operator()(const std::string&) 中搜索子字符串并计算 npos'es

关于c++ - 如何判断一个字符串是否包含另一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16038020/

相关文章:

c++ - boost 程序选项 - 将 multitoken 选项从配置文件附加到命令行

c++ - 创建链表时使用 new 运算符

c++ - VC++ 2015 没有链接,但 VC++ 2012 有

c++ - 没有散​​列的无序映射

c++ - 为什么 std::map::insert 文档引用不存在的关键参数

c# - 浮点精度

c++ - 从访问者更改 boost::variant 基础类型

c++ - 为什么我们可以push_back仅用range定义的子 vector ?

c++ - std::make_shared、std::unique_ptr 和移动构造函数

c++ - 在对其进行线程操作后保存 GDI+ 位图