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

How to decide if one string contains another string

本文关键字:字符串 是否 包含 另一个 一个 何判断 判断      更新时间:2023-10-16

我有一组字符串,然后是第二个字符串。我想遍历这个集合并确定当前字符串是否包含在第二个字符串中。STL或这些包含的工具中有什么工具可以帮助我解决这个问题吗?

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

Usecase:

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::bindboost::lambda传递给std::for_each,将结果与std::string::npos进行比较并计数
您可以在这里找到相关示例
另一种更直接的方法是创建自己的函函数,它将在构造函数中接受string,在operator()(const std::string&)中搜索子字符串并计数npos'

可以使用find_if.

希望对大家有所帮助