查找字符串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 函數
說明:索引
1. 若是string sub = 」abc「;ci
string s = 」cdeabcigld「;字符串
s.find(sub) , s.rfind(sub) 這兩個函數,若是徹底匹配,才返回匹配的索引,即:當s中含有abc三個連續的字母時,才返回當前索引。string
s.find_first_of(sub), s.find_first_not_of(sub), s.find_last_of(sub), s.find_last_not_of(sub) 這四個函數,查找s中含有sub中任意字母的索引。ast
2. 若是沒有查詢到,則返回string::npos,這是一個很大的數,其值不須要知道。配置
特別注意:查詢
find_first_of 函數最容易出錯的地方是和find函數搞混。它最大的區別就是若是在一個字符串str1中查找另外一個字符串str2,若是str1中含有str2中的任何字符,則就會查找成功,而find則不一樣;static