共計(jì) 1417 個(gè)字符,預(yù)計(jì)需要花費(fèi) 4 分鐘才能閱讀完成。
這篇文章將為大家詳細(xì)講解有關(guān) C ++ 中如何使用 string.find() 函數(shù),文章內(nèi)容質(zhì)量較高,因此丸趣 TV 小編分享給大家做個(gè)參考,希望大家閱讀完這篇文章后對(duì)相關(guān)知識(shí)有一定的了解。
#include string #include iostream using namespace std; void main(){ 復(fù)制代碼 代碼如下:
////find 函數(shù)返回類型 size_typestring s(1a2b3c4d5e6f7g8h9i1a2b3c4d5e6f7g8ha9i string flag;string::size_type position;//find 函數(shù) 返回 jk 在 s 中的下標(biāo)位置 position = s.find( jk if (position != s.npos) // 如果沒找到,返回一個(gè)特別的標(biāo)志 c ++ 中用 npos 表示,我這里 npos 取值是 4294967295,{cout position is : position endl;}else{cout Not found the flag + flag;} 復(fù)制代碼 代碼如下:
//find 函數(shù) 返回 flag 中任意字符 在 s 中第一次出現(xiàn)的下標(biāo)位置 flag = c position = s.find_first_of(flag);cout s.find_first_of(flag) is : position endl; 復(fù)制代碼 代碼如下:
// 從字符串 s 下標(biāo) 5 開始,查找字符串 b , 返回 b 在 s 中的下標(biāo) position=s.find(b ,5);cout s.find(b,5) is : position endl; 復(fù)制代碼 代碼如下:
// 查找 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++;} 復(fù)制代碼 代碼如下:
// 查找 flag 中與 s 第一個(gè)不匹配的位置 flag= acb12389efgxyz789 position=flag.find_first_not_of (s);cout flag.find_first_not_of (s) : position endl; 復(fù)制代碼 代碼如下:
// 反向查找,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) 這兩個(gè)函數(shù),如果完全匹配,才返回匹配的索引, 即:當(dāng) s 中含有 abc 三個(gè)連續(xù)的字母時(shí),才返回當(dāng)前索引。s.find_first_of(sub), s.find_first_not_of(sub), s.find_last_of(sub), s.find_last_not_of(sub) 這四個(gè)函數(shù),查找 s 中含有 sub 中任意字母的索引。
2. 如果沒有查詢到,則返回 string::npos,這是一個(gè)很大的數(shù),其值不需要知道。
關(guān)于 C ++ 中如何使用 string.find() 函數(shù)就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。