c++ string rfind find函数

1)size_t find (const string& str, size_t pos = 0) const; //查找对象–string类对象
(2)size_t find (const char s, size_t pos = 0) const; //查找对象–字符串

(3)size_t find (const char
s, size_t pos, size_t n) const; //查找对象–字符串的前n个字符
(4)size_t find (char c, size_t pos = 0) const; //查找对象–字符
结果:找到 – 返回 第一个字符的索引

string::rfind(string, pos) 是从pos开始由右往左找,返回最后一次出现string的位置。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>       // std::cout
#include <string> // std::string

int main ()
{
std::string str ("There are two needles in this haystack with needles.");
std::string str2 ("needle");

// different member versions of find in the same order as above:
std::size_t found = str.find(str2);
if (found!=std::string::npos)
std::cout << "first 'needle' found at: " << found << '\n';

found=str.find("needles are small",found+1,6);
if (found!=std::string::npos)
std::cout << "second 'needle' found at: " << found << '\n';

found=str.find("haystack");
if (found!=std::string::npos)
std::cout << "'haystack' also found at: " << found << '\n';

found=str.find('.');
if (found!=std::string::npos)
std::cout << "Period found at: " << found << '\n';

// let's replace the first needle:
str.replace(str.find(str2),str2.length(),"preposition"); //replace 用法
std::cout << str << '\n';

return 0;


结果:
first 'needle' found at: 14
second 'needle' found at: 44
'haystack' also found at: 30
Period found at: 51
There are two prepositions in this haystack with needles
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

// string::rfind
#include <iostream>
#include <string>
#include <cstddef>
using namespace std;
int main ()
{
std::string str ("The sixth sick sheik's sixth sheep's sick.");
std::string key ("sixth");
//从起始位置 从右往左找
std::size_t found = str.rfind(key,3);
if (found!=std::string::npos)
str.replace (found,key.length(),"seventh");

std::cout << str << '\n';

return 0;
}