在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
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第一次出现的位置
共同点: 查找成功时返回所在位置,失败返回string::npos的值,string::npos一般是MAX_INT(即2^32 - 1)
差异: find(): 查找字符串中第一次出现字符c、字符串s的位置; find_first_of(): 查找字符串中字符c、字符数组s中任意一个字符第一次出现的位置。
|
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论