一、定义
string (1) |
size_t find (const string& str, size_t pos = 0) const; |
---|---|
c-string (2) |
size_t find (const char* s, size_t pos = 0) const; |
buffer (3) |
size_t find (const char* s, size_t pos, size_t n) const; |
character (4) |
size_t find (char c, size_t pos = 0) const; |
查找字符串中第一次出现 str 的位置并返回。当参数pos被指定时,查找只从pos的位置及其后进行,忽略字符串中pos之前的字符
不同于find_first_of方法,当需要查找的参数为多个字符时,必须全部匹配,才返回pos
二、参数
- str
- 需要查找的字符串
- pos
- 从被搜索字符串的第几个字符开始搜索
如果大于被查找字符串的长度,将不会匹配到
注意:字符串的位置从0开始计数
- s
- 指向字符数组的指针
如果指定了参数n (3), 只匹配数组中的前n个字符
另外 (2), 支持空字符结尾的字符串: 待查找字符的长度取决于第一个出现的空字符
- n
- 需要匹配序列的前几个字符
- c
- 被查找的单个字符
三、返回值
第一次匹配到的字符位置,如果没找到,返回 string::npos
size_t 是无符号整形,等同于string::size_type
示例:
// string::find #include <iostream> // std::cout #include <string> // std::string int main () { std::string str ("There are two needles in this haystack with needles."); std::string str2 ("needle"); // 如下调用了两种find方法: //直接查找字符串"needle" ----string(1) std::size_t found = str.find(str2); if (found!=std::string::npos) std::cout << "first 'needle' found at: " << found << ' '; // 从found+1的位置开始查找,6代表只查找"needles are small"的前6个即"needle" ---buffer(3) found=str.find("needles are small",found+1,6); if (found!=std::string::npos) std::cout << "second 'needle' found at: " << found << ' '; found=str.find("haystack"); if (found!=std::string::npos) std::cout << "'haystack' also found at: " << found << ' '; found=str.find('.'); if (found!=std::string::npos) std::cout << "Period found at: " << found << ' '; // 替换第一个"needle" str.replace(str.find(str2),str2.length(),"preposition"); std::cout << str << ' '; return 0; }
运行结果:
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.