形式
- size_t find ( const string& str, size_t pos = 0 ) const;
- size_t find ( const char* s, size_t pos = 0 ) const;
- size_t find ( char c, size_t pos = 0 ) const;
- size_t find ( const **char s , size_t pos, size_t n** ) const;*
参数说明
- pos 查找的起始位置
- n 待查找字符串的前n个字符
使用样例
string str1( “ the usage of find can you use it “);
string str2( “ the “);
注意
- size_t 是 std::size_t 长度类型
- string 中 find() 返回值是字母在串中的位置(下标而不是迭代器)
- 若没找到,那么会返回一个特别的标记npos(可以看成是一个int型的数)**
例子演示
👀1.size_t find ( const **string& str, size_t pos = 0 ) const; 形参是字符串**
作用:在串str1中查找串str2,并返回str1中的str2的首个字符地址下标
string str1( "the usage of find can you use it");
string str2( "find");
std::size_t pos;
pos=str1.find(str2); //str2是字符串
作用:在串str1的第5个字符开始**查找str2,并返回str1中的str2的首个字符地址下标
string str1( "the usage of find can you use it");
string str2( "find");
std::size_t pos;
pos=str1.find(str2,5); //str2是字符串
👀2.size_t find ( const char* s, size_t pos = 0 ) const; 形参是字符数组
作用:在串str1中查找字符数组”usage”,并返回返回”usage”在str1中的下标位置
string str1( "the usage of find can you use it");
string str2( "find");
std::size_t pos;
pos=str1.find("usage"); //"usage"是字符数组
👀3.size_t find ( char c, size_t pos = 0 ) const; 形参是字符
作用:在串str1中查找字符 o,并返回 o 的地址下标位置
注意
字符或者字符串都可以正常使用
string str1( "the usage of find can you use it");
string str2( "find");
std::size_t pos;
pos=str1.find("o"); //"o"是字符串
pos=str1.find("o"); //'o'是字符
👀4.size_t find ( const **char s , size_t pos, size_t n ) const; 形参是字符数组*
作用:从str1中的第二个字符开始查找of big的前两个字符
解释:
- string str1( “the usage of find can you use it”);
- string str2( “the”);
- 第一句:str1的第二个字符开始,指的是 th**e usage of find can you use it 从e开始 **
- 第二句:str2的前两个字符,指的是 of** big 中的 **of
**
string str1( "the usage of find can you use it");
string str2( "the");
std::size_t pos;
pos=str1.find("of big",2,2);
结果演示
# include<iostream>
# include<algorithm>
using namespace std;
int main(void)
{
string str1("the usage of find can you use it");
string str2("the");
std::size_t pos;
pos = str1.find(str2); //从串str1中查找时str2,返回str2中首个字符在str1中的地址
pos = str1.find(str2, 5); //从str1的第5个字符开始查找str2
pos = str1.find("usage"); //如果"usage"在str1中查找到,返回u在str1中的位置
pos = str1.find('o'); //查找字符o并返回地址
pos = str1.find("e big", 2, 2); //从str1中的第二个字符开始查找of big的前两个字符
}
/*
str1="the usage of find can you use it"
str2="the"
0
4294967295
4
10
2
*/