深入C++ string.find()函數(shù)的用法總結(jié)
發(fā)布日期:2022-01-02 17:47 | 文章來源:gibhub
#include <iostream>
using namespace std;
void main()
{
復制代碼 代碼如下:
////find函數(shù)返回類型 size_type
string s("1a2b3c4d5e6f7g8h9i1a2b3c4d5e6f7g8ha9i");
string flag;
string::size_type position;
//find 函數(shù) 返回jk 在s 中的下標位置
position = s.find("jk");
if (position != s.npos) //如果沒找到,返回一個特別的標志c++中用npos表示,我這里npos取值是4294967295,
{
cout << "position is : " << position << endl;
}
else
{
cout << "Not found the flag" + flag;
}
復制代碼 代碼如下:
//find 函數(shù) 返回flag 中任意字符 在s 中第一次出現(xiàn)的下標位置
flag = "c";
position = s.find_first_of(flag);
cout << "s.find_first_of(flag) is : " << position << endl;
復制代碼 代碼如下:
//從字符串s 下標5開始,查找字符串b ,返回b 在s 中的下標
position=s.find("b",5);
cout<<"s.find(b,5) is : "<<position<<endl;
復制代碼 代碼如下:
//查找s 中flag 出現(xiàn)的所有位置。
flag="a";
position=0;
int i=1;
while((position=s.find_first_of(flag,position))!=string::npos)
{
//position=s.find_first_of(flag,position);
cout<<"position "<<i<<" : "<<position<<endl;
position++;
i++;
}
復制代碼 代碼如下:
//查找flag 中與s 第一個不匹配的位置
flag="acb12389efgxyz789";
position=flag.find_first_not_of (s);
cout<<"flag.find_first_not_of (s) :"<<position<<endl;
復制代碼 代碼如下:
//反向查找,flag 在s 中最后出現(xiàn)的位置
flag="3";
position=s.rfind (flag);
cout<<"s.rfind (flag) :"<<position<<endl;
}
說明:
1.如果string sub = ”abc“;
string s = ”cdeabcigld“;
s.find(sub) , s.rfind(sub) 這兩個函數(shù),如果完全匹配,才返回匹配的索引,即:當s中含有abc三個連續(xù)的字母時,才返回當前索引。
s.find_first_of(sub), s.find_first_not_of(sub), s.find_last_of(sub), s.find_last_not_of(sub) 這四個函數(shù),查找s中含有sub中任意字母的索引。
2.如果沒有查詢到,則返回string::npos,這是一個很大的數(shù),其值不需要知道。
版權(quán)聲明:本站文章來源標注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務器上建立鏡像,否則將依法追究法律責任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學習參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。
相關(guān)文章