C++string中find,find_first_of和find_last_of的用法


1. size_t find (const string& str, size_t pos = 0)

str.find(str1)

說明:從pos(默認是是0,即從頭開始查找)開始查找,找到第一個和str1相匹配的子串,返回該子串的起始索引位置;如果沒有找到則返回string::npos
參考:find函數:http://www.cplusplus.com/reference/string/string/find/

2. size_t find_first_of (const string& str, size_t pos = 0)

str.find_first_of(str1)

說明:從pos(默認是是0,即從頭開始查找)開始查找,找到第一個和str1相匹配的子串,返回該子串的起始索引位置;如果沒有找到則返回string::npos
參考:find_first_of函數:http://www.cplusplus.com/reference/string/string/find_first_of/

3.size_t find_last_of (const string& str, size_t pos = npos)

str.find_last_of(str1)

說明:從npos(默認是字符串最后一個,即從后向前查找)開始查找,找到第一個和str1相匹配的子串,返回該子串的最后一個字符的索引位置;如果沒有找到則返回string::npos
參考: find_last_of函數http://www.cplusplus.com/reference/string/string/find_last_of/

舉例如下:

#include<iostream>          
using namespace std;        
                            
int main(void)              
{                           
    string s = "一蓑煙雨任平生。";
    int len = s.size();     
    int count = s.size() / string("一").size();
    cout << "len = " << len << ", count = " << count << endl;
    cout << "find:平: pos = " << s.find("平") << endl;
    cout << "find_first_of:平: pos = " << s.find_first_of("平") << endl;
    cout << "find_last_of:平: pos = " << s.find_last_of("平") << endl;
    int pos = s.find("平", 9);                                                                                                                          
    cout << "pos:" << pos << endl;
    cout << "。: pos = " << s.find("。") << endl;
    cout << "。: pos = " << s.find_last_of("。") << endl;
    return 0;               
} 

結果:

len = 24, count = 8
find:平: pos = 15
find_first_of:平: pos = 15
find_last_of:平: pos = 17
pos:15
。: pos = 21
。: pos = 23

總結:

C++中一個中文字符(包括漢字和中文符號)在字符串中的長度是3。在一個字符
串中查找中文字符的時候最好不要用find_last_of,因為用find_last_of返回的
是這個中文字符串的最后一個pos,而不是第一個,極容易出錯。如上述例子如果
判斷一句話是否是以句號結尾,如果用find_last_of進行查找會得到23而一個句
號的長度是3,加起來會大於整個字符串的長度,主要原因還是容易忘記他是子
串的最后一個pos,如果用find或者find_first_of,出錯概率較低。


免責聲明!

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



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