牛骨文教育服务平台(让学习变的简单)
博文笔记

C++中find()函数的使用方法

创建时间:2017-03-23 投稿人: 浏览次数:7269

转载自: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   示例: [cpp] view plain copy
  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 << " ";  
  13.   
  14.   found=str.find("needles are small",found+1,6);  
  15. //在str中的第(found+1)位开始搜索,搜索"needles are small"字符串中的前6位,找到索引位置。
  16.   if (found!=std::string::npos)  
  17.     std::cout << "second "needle" found at: " << found << " ";  
  18.   
  19.   found=str.find("haystack");  
  20.   if (found!=std::string::npos)  
  21.     std::cout << ""haystack" also found at: " << found << " ";  
  22.   
  23.   found=str.find(".");  
  24.   if (found!=std::string::npos)  
  25.     std::cout << "Period found at: " << found << " ";  
  26.   
  27.   // let"s replace the first needle:  
  28.   str.replace(str.find(str2),str2.length(),"preposition");  //replace 用法  
  29.   std::cout << str << " ";  
  30.   
  31.   return 0;  
  32. }  

结果: 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
那么这个if (found!=std::string::npos) 中std::string::npos是什么意思呢?大概意思就是表示string的结束位子。 具体看这里:http://blog.csdn.net/jiejinquanil/article/details/51789682     其他还有  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"的索引)   其他同理

声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。