C++字符串详解(三) 字符串的查找
生活随笔
收集整理的這篇文章主要介紹了
C++字符串详解(三) 字符串的查找
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1) find() 函數
find() 函數用于在 string 字符串中查找子字符串出現的位置,它其中的兩種原型為:
size_t find (const string& str, size_t pos = 0) const;
size_t find (const char* s, size_t pos = 0) const;
第一個參數為待查找的子字符串,它可以是 string 字符串,也可以是C風格的字符串。第二個參數為開始查找的位置(下標);如果不指明,則從第0個字符開始查找。
#include <iostream> #include <string> using namespace std; int main(){string s1 = "first second third";string s2 = "second";int index = s1.find(s2,5);if(index < s1.length())cout<<"Found at index : "<< index <<endl;elsecout<<"Not found"<<endl;return 0; }運行結果:
Found at index : 6
find() 函數最終返回的是子字符串第一次出現在字符串中的起始下標。本例最終是在下標6處找到了 s2 字符串。如果沒有查找到子字符串,那么會返回一個無窮大值 4294967295。
2) rfind() 函數
rfind() 和 find() 很類似,同樣是在字符串中查找子字符串,不同的是 find() 函數從第二個參數開始往后查找,而 rfind() 函數則最多查找到第二個參數處,如果到了第二個參數所指定的下標還沒有找到子字符串,則返回一個無窮大值4294967295。
#include <iostream> #include <string> using namespace std; int main(){string s1 = "first second third";string s2 = "second";int index = s1.rfind(s2,6);if(index < s1.length())cout<<"Found at index : "<< index <<endl;elsecout<<"Not found"<<endl;return 0; }find_first_of() 函數用于查找子字符串和字符串共同具有的字符在字符串中首次出現的位置。請看下面的代碼:
總結
以上是生活随笔為你收集整理的C++字符串详解(三) 字符串的查找的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 爬百度图片
- 下一篇: C++引用入门教程(一)