日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

C++字符串详解(三) 字符串的查找

發布時間:2025/4/5 c/c++ 20 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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() 函數
    find_first_of() 函數用于查找子字符串和字符串共同具有的字符在字符串中首次出現的位置。請看下面的代碼:
  • #include <iostream> #include <string> using namespace std; int main(){string s1 = "first second second third";string s2 = "asecond";int index = s1.find_first_of(s2);if(index < s1.length())cout<<"Found at index : "<< index <<endl;elsecout<<"Not found"<<endl;return 0; } 運行結果: Found at index : 3本例中 s1 和 s2 共同具有的字符是 ’s’,該字符在 s1 中首次出現的下標是3,故查找結果返回3。

    總結

    以上是生活随笔為你收集整理的C++字符串详解(三) 字符串的查找的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。