繁体   English   中英

反向字符串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, " \n\t");
// 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 = " \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
}

我很好奇为什么basic_string不能自己定义rfind_first_of和朋友。 我认为应该。 无论这是一种非递归(请参见ildjarn的答案)实现,都应满足此问题的要求。 它可以编译,但我尚未对其进行测试。

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);

就像rfind pos如果npos或大于size(),则需要将其设置为size()。

PS:我认为这个问题可以从一些编辑中受益。 对于一个“ find_first_of_not_reverse”来说,这是非常令人误解的。 我认为它应该是rfind_first_of(然后将1加到结果中。)

暂无
暂无

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

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