[英]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.