反向字符串find_first_not_of
Reverse string find_first_not_of
我有一个std::string
,我想找到第一个字符的位置:
- 与以下所有字符不同:
' '
、'n'
和't'
。 - 与我指示的位置相比较低。
因此,例如,如果我有以下string
和职位:
string str("AAA BBB=CCC DDD");
size_t pos = 7;
我希望有可能使用这样的方法:
size_t res = find_first_of_not_reverse(str, pos, " nt");
// now res = 4, because 4 is the position of the space character + 1
我该怎么办?
正如 Bo 所评论的那样,templatetypedef 的答案是 99%;我们只需要std::string::find_last_of
而不是std::string::find_last_not_of
:
#include <cassert>
#include <string>
std::string::size_type find_first_of_not_reverse(
std::string const& str,
std::string::size_type const pos,
std::string const& chars)
{
assert(pos > 1);
assert(pos < str.size());
std::string::size_type const res = str.find_last_of(chars, pos - 1) + 1;
return res == pos ? find_first_of_not_reverse(str, pos - 1, chars)
: res ? res
: std::string::npos;
}
int main()
{
std::string const str = "AAA BBB=CCC DDD";
std::string const chars = " nt";
std::string::size_type res = find_first_of_not_reverse(str, 7, chars); // res == 4
res = find_first_of_not_reverse(str, 2, chars); // res == npos
}
我很好奇为什么basic_string自己没有定义rfind_first_of和朋友。我认为应该。不管这里是一个非递归(参见ildjarn的答案)实现,它应该满足这个问题的要求。它可以编译,但我还没有测试过。
std::string delims = " nt";
reverse_iterator start = rend()-pos-1, found =
std::find_first_of(start,rend(),delims.begin(),delims.end());
return found==rend()?npos:pos-(found-start);
要像 rfind pos 一样,如果它是 npos 或大于 size(),则需要将其设置为 size()。
PS:我认为这个问题可以从一些编辑中受益。对于一个"find_first_of_not_reverse"来说,这是相当误导的。我认为应该是rfind_first_of(然后在结果中添加 1。
相关文章:
- Usages of std::move
- 使用 [] 运算符时"binding reference of type discards qualifiers"
- 如何处理 c++ 中类实现中的"invalid use of non-static data member"?
- 具有变量Number of Arguments的std::函数的矢量
- Capacity of a deque
- Deprecation of _writeBarrier()
- constexpr begin of a std::array
- 如何调整 std::vector of Eigen::MatrixXd 的大小
- C++ "error: invalid use of void expression"
- 我看到"use of undeclared identifier"错误,有人可以告诉我如何解决它吗?
- C++算法标头中,为什么要使用 "!(val < *first)" ?
- 赛通"Cannot take address of memoryview slice"
- C++ Version Of Double.longBitsToDouble
- 收到错误"invalid use of non-static data member 'stu::n' "
- C++ Usage of AsyncCallback
- 错误:"Left of getValue must have class/struct/union"
- Centos7 g++ "to_string is not in a member of std"
- 在C++中使用 Catch 测试框架编译错误"error: expected ';' at end of declaration list"
- C++ 字符串迭代器"find first of"
- "Multiple definition of.." "First defined here"数据结构中的同一行中