string中 find()的應用 (rfind() 類似,只是從反向查找)
原型如下:
(1)size_t find (const string& str, size_t pos = 0) const; //查找對象--string類對象
(2)size_t find (const char* s, size_t pos = 0) const; //查找對象--字符串
(3)size_t find (const char* s, size_t pos, size_t n) const; //查找對象--字符串的前n個字符
(4)size_t find (char c, size_t pos = 0) const; //查找對象--字符
結果:找到 -- 返回 第一個字符的索引
沒找到--返回 string::npos
示例:
1 2 #include <iostream> // std::cout 3 4 #include <string> // std::string 5 6 7 8 int main () 9 10 { 11 12 std::string str ("There are two needles in this haystack with needles."); 13 14 std::string str2 ("needle"); 15 16 17 18 // different member versions of find in the same order as above: 19 20 std::size_t found = str.find(str2); 21 22 if (found!=std::string::npos) 23 24 std::cout << "first 'needle' found at: " << found << '\n'; 25 26 27 28 found=str.find("needles are small",found+1,6); 29 30 if (found!=std::string::npos) 31 32 std::cout << "second 'needle' found at: " << found << '\n'; 33 34 35 36 found=str.find("haystack"); 37 38 if (found!=std::string::npos) 39 40 std::cout << "'haystack' also found at: " << found << '\n'; 41 42 43 44 found=str.find('.'); 45 46 if (found!=std::string::npos) 47 48 std::cout << "Period found at: " << found << '\n'; 49 50 51 52 // let's replace the first needle: 53 54 str.replace(str.find(str2),str2.length(),"preposition"); //replace 用法 55 56 std::cout << str << '\n'; 57 58 59 60 return 0; 61 62 }
結果:
first 'needle' found at: 14
second 'needle' found at: 44
'haystack' also found at: 30
Period found at: 51
There are two prepositions in this haystack with needles
int find_first_of(char c, int pos = 0) const;//從pos開始查找字符c第一次出現的位置
int find_first_of(const char *s, int pos = 0) const; //從pos開始查找當前串中第一個在s的前n個字符組成的數組里的字符的位置
int find_first_of(const char *s, int pos, int n) const;
int find_first_of(const string &s,int pos = 0) const;
共同點:
查找成功時返回所在位置,失敗返回string::npos的值,string::npos一般是MAX_INT(即2^32 - 1)
差異:
find(): 查找字符串中第一次出現字符c、字符串s的位置;
find_first_of(): 查找字符串中字符c、字符數組s中任意一個字符第一次出現的位置。
類似的,還有rfind()和find_last_of(),以及find_first_not_of(), find_last_not_of().