https://blog.csdn.net/DLUTBruceZhang/article/details/16370439string中 find()的应用 (rfind() 类似,只是从反向查找)原型如下:(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::npos示例:
1
2 #include <iostream> // std::cout
3
4 #include <string> // std::string
5
6
7
8 int main ()
9
10 {
11
12 std::string str ("There are two needles in this haystack with needles.");
13
14 std::string str2 ("needle");
15
16
17
18 // different member versions of find in the same order as above:
19
20 std::size_t found = str.find(str2);
21
22 if (found!=std::string::npos)
23
24 std::cout << "first 'needle' found at: " << found << '\n';
25
26
27
28 found=str.find("needles are small",found+1,6);
29
30 if (found!=std::string::npos)
31
32 std::cout << "second 'needle' found at: " << found << '\n';
33
34
35
36 found=str.find("haystack");
37
38 if (found!=std::string::npos)
39
40 std::cout << "'haystack' also found at: " << found << '\n';
41
42
43
44 found=str.find('.');
45
46 if (found!=std::string::npos)
47
48 std::cout << "Period found at: " << found << '\n';
49
50
51
52 // let's replace the first needle:
53
54 str.replace(str.find(str2),str2.length(),"preposition"); //replace 用法
55
56 std::cout << str << '\n';
57
58
59
60 return 0;
61
62 }
结果:first 'needle' found at: 14second 'needle' found at: 44'haystack' also found at: 30Period found at: 51There are two prepositions in this haystack with needleshttps://blog.csdn.net/Richard_123/article/details/51140229
int find_first_of(char c, int pos = 0) const;//从pos开始查找字符c第一次出现的位置
int find_first_of(const char s, int pos = 0) const; //从pos开始查找当前串中第一个在s的前n个字符组成的数组里的字符的位置
int find_first_of(const char s, int pos, int n) const;
int find_first_of(const string &s,int pos = 0) const;
共同点:
查找成功时返回所在位置,失败返回string::npos的值,string::npos一般是MAX_INT(即2^32 - 1)
差异:
find(): 查找字符串中第一次出现字符c、字符串s的位置;
find_first_of(): 查找字符串中字符c、字符数组s中任意一个字符第一次出现的位置。
类似的,还有rfind()和find_last_of(),以及find_first_not_of(), find_last_not_of().
原文链接: https://www.cnblogs.com/shilipojianshen/p/13279455.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/200209
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!