反向字符串find_first_not_of

Reverse string find_first_not_of

本文关键字:first of not find 字符串      更新时间:2023-10-16

我有一个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。