C++中find()函数和rfind()函数的用法

本文转载自http://blog.csdn.net/youxin2012/article/details/9162415
string中 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 #include <iostream>       // std::cout  
 2 #include <string>         // std::string  
 3   
 4 int main ()  
 5 {  
 6   std::string str ("There are two needles in this haystack with needles.");  
 7   std::string str2 ("needle");  
 8   
 9   // different member versions of find in the same order as above:  
10   std::size_t found = str.find(str2);  
11   if (found!=std::string::npos)  
12     std::cout << "first 'needle' found at: " << found << '\n';  
13   
14   found=str.find("needles are small",found+1,6);  
15   if (found!=std::string::npos)  
16     std::cout << "second 'needle' found at: " << found << '\n';  
17   
18   found=str.find("haystack");  
19   if (found!=std::string::npos)  
20     std::cout << "'haystack' also found at: " << found << '\n';  
21   
22   found=str.find('.');  
23   if (found!=std::string::npos)  
24     std::cout << "Period found at: " << found << '\n';  
25   
26   // let's replace the first needle:  
27   str.replace(str.find(str2),str2.length(),"preposition");  //replace 用法  
28   std::cout << str << '\n';  
29   
30   return 0;  
31 }

结果:first 'needle' found at: 14second 'needle' found at: 44'haystack' also found at: 30Period found at: 51There are two prepositions in this haystack with needles其他还有 find_first_of(), find_last_of(), find_first_not_of(), find_last_not_of()作用是查找 字符串中任一个字符满足的查找条件string snake1("cobra");int where = snake1.find_first_of("hark");返回3 因为 "hark"中 各一个字符 在 snake1--cobra 中第一次出现的是 字符'r'(3为 cobra 中'r'的索引)同理:int where = snake1.find_last_of("hark");返回4 因为 "hark"中 各一个字符 在 snake1--cobra 中最后一次出现的是 字符'a'(3为 cobra 中'r'的索引)其他同理原文链接: https://www.cnblogs.com/cynthia-dcg/p/6178650.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/245776

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月14日 上午1:04
下一篇 2023年2月14日 上午1:04

相关推荐