【问题标题】:C++ STL reverse string search, down to a bounding indexC++ STL 反向字符串搜索,向下到边界索引
【发布时间】:2021-01-21 05:05:53
【问题描述】:

考虑

std::string reasonStr

还有一个电话

reasonStr.find(").", sepIndex)

reasonStr 中找到")." 的第一次出现,但最早出现在sepIndex。 我想在sepIndex 找到最后 个这样的事件。 但是一个电话

reasonStr.rfind(").", sepIndex)

取而代之的是seems tosepIndex 开始从右到左搜索,向下搜索到0。此外,

string::size_type s = reasonStr.rfind(").");
s = s < sepIndex ? string::npos : s;

获得了想要的结果,但可能搜索得太远(即低于sepIndex)。或者,我可以在 reasonStr.substr(sepIndex) 内部搜索,但这似乎是不必要的副本。

总之,这些函数有参数从哪里开始搜索,但没有参数在哪里结束。我想在告诉在哪里结束搜索的字符串上使用这样的 STL 函数。

更准确地说,我想使用 STL 以相反的顺序找到一个子字符串,并指定一个可能出现的下限索引,无需首先获取字符串的子字符串搜索。

C++20 STL 中有这样的函数吗?

我什至在 Boost 库中寻找它,但找不到它。指向 Boost 也会有所帮助,以防标准未提供它。

编辑/解决方案

我接受了第一个 answer,它展示了如何使用 std::string_view 来做到这一点。我去了:

string::size_type s = string_view(reasonStr.begin() + sepIndex, reasonStr.end()).rfind(").");
if (s != string_view::npos)
    s += sepIndex;

【问题讨论】:

  • 你考虑过string::find_last_of吗?
  • 是的,但是那没有找到完整的字符串,而是any字符串中出现的字符,对吧?
  • 是的,没错。
  • 类似构造正确的std::string_view 然后rfind?
  • 你可以考虑找第一个字符,检查下一个,反正boost::algorithm::find_last可以用的话可以选择。

标签: c++ string search stl c++20


【解决方案1】:

要查找从 sepIndex 开始的最后一次出现,您可以创建一个 std::string_view 并反向搜索。它不分配(复制)任何东西,它只是指向原始数据。这是一个重要的注意事项,因为您必须确保 string_view 引用现有对象 - 如果 string_view 比它指向的 string 寿命更长,则使用 string_view 是未定义的行为。

#include <iostream>
#include <string>
#include <string_view>

int main()
{
    std::string s = "This ) is a string ). with ). three matches";
    std::size_t sepIndex = 18;
    std::string pattern = ").";
    std::string_view sv(s.begin() + sepIndex, s.end());

    auto pos = sv.rfind(pattern);
    if (pos != std::string_view::npos) {
        std::cout << sepIndex + pos << "\n";
    }
    else {
        std::cout << "No match found\n";
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-31
    • 2017-12-02
    相关资源
    最近更新 更多