C++ STL 反向字符串搜索,向下到边界索引
C++ STL reverse string search, down to a bounding index
考虑
std::string reasonStr
和一个电话
reasonStr.find(").", sepIndex)
查找 reasonStr
中第一次出现的 ")."
,但最早出现在 sepIndex
。
我想找到 last 这样的事件,最早发生在 sepIndex
。
但是一个电话
reasonStr.rfind(").", sepIndex)
而不是 seems to 从 sepIndex
开始从右到左搜索,直到 0。此外,
string::size_type s = reasonStr.rfind(").");
s = s < sepIndex ? string::npos : s;
获得了想要的结果,但可能会搜索得太远(即低于 sepIndex
)。或者,我可以在 reasonStr.substr(sepIndex)
中搜索,但这似乎是一个不必要的副本。
总之,这些函数具有从哪里开始搜索的参数,但没有从哪里结束搜索的参数。我想在字符串上使用这样的 STL 函数来告诉在哪里结束搜索。
更准确地说,我想使用 STL 以相反的顺序查找子字符串,并指定一个可能出现的索引下限,没有先取一个要搜索的字符串的子字符串。
C++20 STL 中有这样的函数吗?
我什至在Boost库中找过,也没有找到。指向 Boost 也会有所帮助,以防标准不提供它。
编辑/解决方案
我接受了第一个 ,它展示了如何使用 std::string_view
来做到这一点。我去了:
string::size_type s = string_view(reasonStr.begin() + sepIndex, reasonStr.end()).rfind(").");
if (s != string_view::npos)
s += sepIndex;
要查找在 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";
}
}
考虑
std::string reasonStr
和一个电话
reasonStr.find(").", sepIndex)
查找 reasonStr
中第一次出现的 ")."
,但最早出现在 sepIndex
。
我想找到 last 这样的事件,最早发生在 sepIndex
。
但是一个电话
reasonStr.rfind(").", sepIndex)
而不是 seems to 从 sepIndex
开始从右到左搜索,直到 0。此外,
string::size_type s = reasonStr.rfind(").");
s = s < sepIndex ? string::npos : s;
获得了想要的结果,但可能会搜索得太远(即低于 sepIndex
)。或者,我可以在 reasonStr.substr(sepIndex)
中搜索,但这似乎是一个不必要的副本。
总之,这些函数具有从哪里开始搜索的参数,但没有从哪里结束搜索的参数。我想在字符串上使用这样的 STL 函数来告诉在哪里结束搜索。
更准确地说,我想使用 STL 以相反的顺序查找子字符串,并指定一个可能出现的索引下限,没有先取一个要搜索的字符串的子字符串。
C++20 STL 中有这样的函数吗?
我什至在Boost库中找过,也没有找到。指向 Boost 也会有所帮助,以防标准不提供它。
编辑/解决方案
我接受了第一个 std::string_view
来做到这一点。我去了:
string::size_type s = string_view(reasonStr.begin() + sepIndex, reasonStr.end()).rfind(").");
if (s != string_view::npos)
s += sepIndex;
要查找在 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";
}
}