npos类型: static const size_t npos = -1;
find()类型声明:
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; |
用法示例:
#include <iostream>
#include <string>
using namespace std;
int main (){
string str ("There are two needles in this haystack with needles.");
string str2 ("needle");
// different member versions of find in the same order as above:
//1
size_t found = str.find(str2);
if (found!=string::npos)
cout << "first 'needle' found at: " << found << '\n';
//3
found=str.find("needles are small",found+1,6);
//从上次找到的位置的下一个位置开始查找 "needles are small"的前六个字符
if (found!=string::npos)
cout << "second 'needle' found at: " << found << '\n';
//2
found=str.find("haystack");
if (found!=string::npos)
cout << "'haystack' also found at: " << found << '\n';
//4
found=str.find('.');
if (found!=string::npos)
cout << "Period found at: " << found << '\n';
// let's replace the first needle:
str.replace(str.find(str2),str2.length(),"preposition");
//从str.find(str2)开始 str2.length()长度 的string串被替换为 "preposition"
cout << str << '\n';
return 0;
}
运行结果:
参考:
http://www.cplusplus.com/reference/string/string/find/