简体   繁体   English

反向字符串find_first_not_of

[英]Reverse string find_first_not_of

I have a std::string and I want to find the position of the first character that: 我有一个std::string ,我想找到第一个字符的位置:

  • Is different from all the following characters: ' ' , '\\n' and '\\t' . 与以下所有字符不同: ' ''\\n''\\t'
  • Has lower position from that indicated by me. 位置比我指示的位置低。

So, for example if I have the following string and position: 因此,例如,如果我具有以下string和位置:

string str("AAA BBB=CCC DDD");
size_t pos = 7;

I want to have the possibility to use a method like this: 我想有可能使用这样的方法:

size_t res = find_first_of_not_reverse(str, pos, " \n\t");
// now res = 4, because 4 is the position of the space character + 1

How can I do? 我能怎么做?

As Bo commented, templatetypedef's answer was 99% of the way there; 正如Bo所说,templatetypedef的答案是99%的答案。 we just need std::string::find_last_of rather than std::string::find_last_not_of : 我们只需要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 = " \n\t";
    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
}

I was curious why basic_string does not define rfind_first_of and friends myself. 我很好奇为什么basic_string不能自己定义rfind_first_of和朋友。 I think it should. 我认为应该。 Regardless here is a non-recursive (see ildjarn's answer) implementation that should fulfill the requirements of this question. 无论这是一种非递归(请参见ildjarn的答案)实现,都应满足此问题的要求。 It compiles but I've not tested it. 它可以编译,但我尚未对其进行测试。

std::string delims = " \n\t";
reverse_iterator start = rend()-pos-1, found = 
std::find_first_of(start,rend(),delims.begin(),delims.end());
return found==rend()?npos:pos-(found-start);

To be like rfind pos needs to be set to size() if it's npos or greater than size(). 就像rfind pos如果npos或大于size(),则需要将其设置为size()。

PS: I think this question could benefit from some editing. PS:我认为这个问题可以从一些编辑中受益。 For one "find_first_of_not_reverse" is pretty misleading. 对于一个“ find_first_of_not_reverse”来说,这是非常令人误解的。 It should be rfind_first_of I think (and then add 1 to the result.) 我认为它应该是rfind_first_of(然后将1加到结果中。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM