如何"reset" std::string的查找成员函数,一旦它到达字符串的末尾

How to "reset" the find member function of std::string once it reaches end of string

本文关键字:字符串 函数 std reset string 查找 如何 成员      更新时间:2023-10-16

有没有一种方法可以"重置"函数std::string::find,再次查看字符串的开头,类似于在I/o流中设置文件指针?谢谢

您的假设是错误的。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);

实际上find搜索给定索引后的第一个匹配项。这是默认的原型:

size_t find (const string& str, size_t pos = 0) const noexcept;

默认情况下,它开始查看字符串的索引0,因此:

str.find(str2);

正在搜索str中首次出现的str2。如果没有发现任何内容,则返回std::string::npos

你可以使用这样的功能:

str.find(str2, 4);

它将从索引4开始搜索str中第一个出现的str2。如果字符串str的字符少于4个,它将再次返回std::string::npos