6.5C++查找字符串


參考:http://www.weixueyuan.net/view/6394.html

總結:

  find函數可以在字符串中查找子字符串中出現的位置。該函數有兩個參數,第一個參數是待查找的子字符串,第二個參數是表示開始查找的位置,如果第二個參數不指名的話則默認從0開始查找,也即從字符串首開始查找。

  rfind函數與find函數很類似,同樣是在字符串中查找子字符串,不同的是find函數是從第二個參數開始往后查找,而rfind函數則是最多查找到第二個參數處,如果到了第二個參數所指定的下標還沒有找到子字符串,則返回一個無窮大值4294967295。

    注意:rfind函數是查到第二個參數,而不是字符串取到第2個參數,然后從此子字符串中查找,具體見例子。

        例2中rfind函數第二個參數是6,也就是說起始查找從0到6,如果找到了則返回下標,否則返回一個無窮大。本例中剛好在下標6的時候找到了子字符串s2,故而返回下標6。

  find_first_of函數是用於查找子字符串和字符串共同具有的字符在字符串中出現的位置。

  find_first_not_of函數則相反,它查找的是在s1字符串但不在s2字符串中的首位字符的下標,如果查找不成功則返回無窮大。

    

find函數可以在字符串中查找子字符串中出現的位置。該函數有兩個參數,第一個參數是待查找的子字符串,第二個參數是表示開始查找的位置,如果第二個參數不指名的話則默認從0開始查找,也即從字符串首開始查找。

例1:

#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;
    else
        cout<<"Not found"<<endl;
    return 0;
}

 

函數最終返回的是子字符串出現在字符串中的起始下標。例1程序最終實在下標6處找到了s2字符串。如果沒有查找到子字符串,則會返回一個無窮大值4294967295。

rfind函數與find函數很類似,同樣是在字符串中查找子字符串,不同的是find函數是從第二個參數開始往后查找,而rfind函數則是最多查找到第二個參數處,如果到了第二個參數所指定的下標還沒有找到子字符串,則返回一個無窮大值4294967295。

例2:

#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;
    else
        cout<<"Not found"<<endl;
    return 0;
}

 

例2中rfind函數第二個參數是6,也就是說起始查找從0到6,如果找到了則返回下標,否則返回一個無窮大。本例中剛好在下標6的時候找到了子字符串s2,故而返回下標6。

find_first_of函數是用於查找子字符串和字符串共同具有的字符在字符串中出現的位置。

例3:

#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;
    else
        cout<<"Not found"<<endl;
    return 0;
}

 

本例中s1和s2共同具有的字符是’s’,該字符在s1中首次出現的下標是3,故查找結果返回3。

而find_first_not_of函數則相反,它查找的是在s1字符串但不在s2字符串中的首位字符的下標,如果查找不成功則返回無窮大。

例4:

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string s1 = "secondasecondthird";
    string s2 = "asecond";
    int index = s1.find_first_not_of(s2);
    if(index < s1.length())
        cout<<"Found at index : "<< index <<endl;
    else
        cout<<"Not found"<<endl;
    return 0;
}

 

在本例中在s1但是不在s2中的首字符是’t’,其所在下標為13,故而返回下標13。 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM