一:find()函数用法详解
函数原型:
size_t find(const string &str, size_t pos = 0) const
size_t find (const char *s, size_t pos, size_t n) const
size_t find (const char *s, size_t pos = 0) const
size_t find (char c,size_t pose = 0) const
举例说明:
string s1 = "how to use the find";
string s2 = "use";
那么,我们既可以在 s1 中查找 s2 中的内容,也可以在 s1 自己中查找某个字符或者字符串。最终都是返回查找到的字符(串)在s1中的首地址。
1) size_t found = s1.find(s2); cout << found;
结果为7。也就是‘u’在 s1 中的索引,注意,别忽略了空格。如果不存在这个字符串,那么返回的是一个很大的数。
2)size_t found = s1.find(s2, 3); cout << found;
结果为7。也就是‘u’在 s1 中的索引。此时,是从s1 的第 3 个字符开始寻找
3)size_t found = s1.find("to"); cout << found;
结果为4。如果这样,size_t found = s1.find("to"); cout << found; 结果也是4. 但是如果这样:size_t found = s1.find("tow"); cout << found; 结果为一个很大的值
4)size_t found = s1.find("use",2,2); cout << found;
结果为 7 。表示从 s1 中第二个字符开始寻找 “use” 的前两个字符。此时,只要 “use” 前两个字符满足在 s1 中即可。如果这样:
size_t found = s1.find("usq",2,2); 结果仍然是对的,为7.
二:find_first_of()函数用法详解
函数原型:
size_t find_first_of(const string &str, size_t pos = 0) const
size_t find_first_of (const char *s, size_t pos, size_t n) const
size_t find_first_of (const char *s, size_t pos = 0) const
size_t find_first_of (char c,size_t pose = 0) const
单单从函数的形参来看,基本是类似的,但是,与 find() 函数不同的是,如果在 s1 中查找 s2 ,如果s1 中含有 s2 的任何字符,就查找成功。 比如,size_t found = s1.find_first_of("usetow");
cout << found;
输出结果是 1 。为什么是1 呢?其实这个函数实际返回的是,“usetow” 中第一个出现在 s1 中的那个字符的位置。显然,字符 ‘o’ 是最早的那个出现在 s1 中的。
那如果这样:size_t found = s1.find_first_of("usetow",6);
输出结果就是 7。因为它是从编号为6的字符(即空格)开始查找,找到的是‘u’