std::string 的方法 find,返回值類型是std::string::size_type, 對應的是查找對象在字符串中的位置(從0開始),
如果未查找到,該返回值是一個很大的數據(4294967295),判斷時與 std::string::npos 進行對比
std::string str("abcdefg"); std::string::size_type pos = str.find("abc"); if (pos != std::string::npos) { cout << "Not find" << endl; }
或
std::string str("abcdefg"); if (str.find("abc") != std::string::npos) { cout << "Not find" << endl; }
很多同學由於經常使用 CString 的緣故,喜歡這樣寫
std::string str("abcdefg"); int pos = str.find("abc"); if (pos < 0) { cout << "Not find" << endl; }
這樣寫理論上也是可以的,因為 size_type 相當於 unsigned int類型,最大值4294967295強制轉換為int型,就是-1
但下面的寫法是錯誤的:
std::string str("abcdefg"); if (str.find("abc") < 0) //錯誤,應該寫成 != std::string::npos { cout << "Not find" << endl; }
最后,建議使用size_type,這樣可以適應不同的平台。因為int 類型的大小會根據不同平台而不同。
拓展:
s.find(s2) 第一次出現的位置
s.rfind 最后一次出現的位置
s.find_first_of(s2) 任何一個字符第一次出現的位置
s.find_last_of 任何一個字符最后一次出現的位置
s.find_first_not_of(s2) 第一個不在s2中的字符所在位置
s.find_last_not_of(s2) 最后一個不在s2中的字符所在位置
《完》