有没有办法可以“重置”函数std :: string :: find再次查看字符串的开头类似于在i / o流中设置文件指针?感谢。
答案 0 :(得分:8)
你的假设是错误的。 find
始终查找第一个匹配项(或指定起始索引后的第一个匹配项)
std::string str("Hello");
size_t x = str.find("l");
assert(x==2);
x = str.find("l");
assert(x==2);
要查找下一场比赛,您必须指定一个开始位置:
x = str.find("l",x+1); //previous x was 2
assert(x==3);
x = str.find("l",x+1); //now x is 3, no subsequent 'l' found
assert(x==std::string::npos);
答案 1 :(得分:3)
实际上find
会在给定索引后搜索第一个匹配项。这是默认原型:
size_t find (const string& str, size_t pos = 0) const noexcept;
默认情况下,它会开始查看字符串的索引0,所以:
str.find(str2);
正在str2
中搜索str
的第一次出现。如果找不到任何内容,则返回std::string::npos
您可以使用以下功能:
str.find(str2, 4);
它将从索引4开始搜索str2
中str
的第一次出现。如果字符串str
少于4个字符,它将再次返回std::string::npos
。