这里写目录标题
- String的查找方法 find
- 使用:
- 返回值:
- 输出结果
- 更多string方法
参考于 c++手册
String的查找方法 find
使用:
std::string str ("There are two needles in this haystack with needles.");
std::string str2 ("needle");
// different member versions of find in the same order as above:
std::size_t found = str.find(str2);
返回值:
返回第一个匹配的第一个字符的位置。
如果没有找到匹配项,该函数返回string:npos。
static const size_t npos = -1;
下面的Size_t是一个无符号整型(与成员类型相同)。
// 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");
// different member versions of find in the same order as above:
std::size_t found = str.find(str2);
if (found!=std::string::npos)
std::cout << "first 'needle' found at: " << found << '\n';
found=str.find("needles are small",found+1,6);
if (found!=-1)
std::cout << "second 'needle' found at: " << found << '\n';
found=str.find("haystack");
if (found!=std::string::npos)
std::cout << "'haystack' also found at: " << found << '\n';
found=str.find('.');
if (found!=std::string::npos)
std::cout << "Period found at: " << found << '\n';
// let's replace the first needle:
str.replace(str.find(str2),str2.length(),"preposition");
std::cout << str << '\n';
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.
上面用了下面的形式
更多string方法
其他方法 | 作用 |
---|---|
string::rfind | Find last occurrence of content in string (public member function) |
string::find_last_of | Find character in string from the end (public member function) |
string::find_first_of | Find character in string from the end (public member function) |
string::find_first_not_of | Find absence of character in string (public member function |
string::find_last_not_of | Find non-matching character in string from the end (public member function) |
string::replace | Replace portion of string (public member function) |
string::substr | Generate substring (public member function) |