1. 程式人生 > >string中的find函式和string::npos的使用

string中的find函式和string::npos的使用

查詢字串a是否包含子串b,
不是用strA.find(strB) > 0而是strA.find(strB) != string:npos
string::size_type pos = strA.find(strB);
if(pos != string::npos){}
-------------------------------------------
int idx = str.find("abc");
if (idx == string::npos)
...
上述程式碼中,idx的型別被定義為int,這是錯誤的,即使定義為 unsigned int 也是錯的,它必須定義為 string::size_type。
npos 是這樣定義的:

static const size_type npos = -1;

因為 string::size_type (由字串配置器 allocator 定義) 描述的是 size,故需為無符號整數型別。因為預設配置器以型別 size_t 作為 size_type,於是 -1 被轉換為無符號整數型別,npos 也就成了該型別的最大無符號值。不過實際數值還是取決於型別 size_type 的實際定義。不幸的是這些最大值都不相同。事實上,(unsigned long)-1 和 (unsigned short)-1 不同(前提是兩者型別大小不同)。因此,比較式 idx == string::npos 中,如果 idx 的值為-1,由於 idx 和字串string::npos 型別不同,比較結果可能得到 false。

要想判斷 find() 的結果是否為npos,最好的辦法是直接比較:

if (str.find("abc") == string::npos) { ... }

錯誤:if(str.find("abc") ) 
注:找不到abc會返回-1,不為0為True。0為False 
------------------------------------------------
複製程式碼  ////find函式返回型別 size_typestring s("1a2b3c4d5e6f7g8h9i1a2b3c4d5e6f7g8ha9i");
string flag;
string::size_type position;

//find 函式 返回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 函式 返回flag 中任意字元 在s 中第一次出現的下標位置 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 出現的所有位置。 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 中最後出現的位置 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) 這兩個函式,如果完全匹配,才返回匹配的索引,即:當s中含有abc三個連續的字母時,才返回當前索引。

     s.find_first_of(sub),   s.find_first_not_of(sub),   s.find_last_of(sub),  s.find_last_not_of(sub)  這四個函式,查詢s中含有sub中任意字母的索引。

2.  如果沒有查詢到,則返回string::npos,這是一個很大的數,其值不需要知道。