尝试使用find last获取最后一个'='的索引返回一个垃圾编号.
size_t index = str.find_last_of('=', 0);
Run Code Online (Sandbox Code Playgroud)
这是字符串,其中有一个'='.
"page id=0 file="simsun.png" chars count=97"
Run Code Online (Sandbox Code Playgroud)
我如何找到最后一个'='的索引?
就此而言string::find_last_of(),指定pos意味着搜索仅包括该位置或之前的字符,忽略其后的任何可能的出现.如果在给定这些限制的情况下无法找到,npos则返回.
完整的细节可以在标准中找到,例如C++11 21.4.7.5:
21.4.7.5
basic_string::find_last_of[string :: find.last.of]
size_type find_last_of(
const basic_string& str,
size_type pos = npos
) const noexcept;效果:
xpos如果可能,确定最高位置,以便以下两个条件获得:
xpos <= pos和xpos < size();traits::eq(at(xpos), str.at(I))对于I由...控制的字符串的某些元素str.返回:
xpos如果函数可以确定这样的值xpos.否则,返回npos.备注:用途
traits::eq().
size_type find_last_of(
charT c,
size_type pos = npos
) const noexcept;返回:
find_last_of(basic_string<charT,traits,Allocator>(1,c),pos).
这是xpos <= pos在第一个问题点导致问题的原因.除非你的字符串实际开头,否则你=的特定表达式将会得到npos结果.这是你看到的大数字,因为它是价值的无符号变体-1.
find_last_of()如果要查找最后一个字符的正确形式是:
size_t index = str.find_last_of('=');
Run Code Online (Sandbox Code Playgroud)
由于pos默认为npos,意味着它考虑整个字符串.