【问题标题】:Using std::search to search substrings in a std::string使用 std::search 搜索 std::string 中的子字符串
【发布时间】:2021-01-03 04:38:37
【问题描述】:

我想使用std::search在字符串中搜索一些子字符串。

我试过这个:

std::string str = "the quick brown fox jumps over the lazy dog";
std::string substr[] = { "fox","dog","bear" };
auto it = std::search(str.begin(), str.end(), substr, substr + 3);
std::cout << "substring found at position :" << (it - str.begin()) << std::endl;

我有这些错误:

operator_surrogate_func:no mathing overloaded function found
Failed to specialize function template 'unknown type std::equal_to<void>::operator()

【问题讨论】:

  • std::search() 在这种情况下所做的是尝试将单个字符与 std::strings 进行比较,这是不可能的,因此会出现错误。
  • std::search 搜索 one 字符串。如果你想从一个数组中搜索三个字符串,你需要使用std::search 和一个循环。

标签: c++ algorithm search substring stdstring


【解决方案1】:

您有一组子字符串,因此您需要单独比较每个子字符串,std::search 一次只能查找一个子字符串。

std::string str = "the quick brown fox jumps over the lazy dog";
std::string substr[] = { "fox","dog","bear" };

for(auto& sstr : substr){
    auto it = std::search(str.begin(), str.end(), sstr.begin(), sstr.end());
    std::cout << "substring found at position :" << (it - str.begin()) << std::endl;
}

请注意,如果未找到子字符串,则返回将是 .end() 迭代器,它指向字符串末尾之后的位置。

【讨论】:

    【解决方案2】:

    因为std::search 的最后两个参数应该是您正在寻找的字符序列的迭代器(更准确地说,您的迭代器和迭代器的引用类型必须具有可比性),以及您的substr 变量如果是std::string 的数组。所以 range [substr, substr+3) 实际上并不代表你的“狐狸”或“狗”或“熊”,而是指向字符串“狐狸”的指针和一个超过数组末尾的指针。

    尝试以下方法:

        std::string str = "the quick brown fox jumps over the lazy dog";
        std::string substr[] = { "fox","dog","bear" };
        auto it = std::search(str.begin(), str.end(), substr[0].begin(), substr[0].end());
        std::cout << "substring found at position :" << (it - str.begin()) << std::endl;
        it = std::search(str.begin(), str.end(), substr[1].begin(), substr[1].end());
        std::cout << "substring found at position :" << (it - str.begin()) << std::endl;
        it = std::search(str.begin(), str.end(), substr[2].begin(), substr[2].end());
        std::cout << "substring found at position :" << (it - str.begin()) << std::endl;
        return 0;
    

    首先它会在你的字符串中搜索“fox”,然后是“dog”,然后是“bear”。未找到“熊”,生成的迭代器指向str.end()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-12-28
      • 2011-01-14
      • 1970-01-01
      • 1970-01-01
      • 2019-10-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多