C++ string中的find()函数
查找字符串s1中是否包含子串s2?
思路:此处需要用到string库中的find函数与npos参数。
(1)string::npos参数
string::npos参数: npos是一个常数,用来表示不存在的位置,npos定义的类型是: string::size_type。npos定义为:static const size_type npos=-1;
(2)find函数
find函数的返回值是整数,假如字符串存在包含关系,其返回值必定不等于npos,但如果字符串不存在包含关系,那么返回值一定是npos。所以,不难想到用if判断语句来实现!
1.string中find()返回值是字母在母串中的位置(下标记录),如果没有找到,那么会返回一个特别的标记npos。(返回值可以看成是一个int型的数)
例:
#include<cstring>
#include<cstdio>
#include<iostream>
using namespace std;
int main()
{
find函数返回类型 size_type
string s("1a2b3c4d5e6f7jkg8h9i1a2b3c4d5e6f7g8ha9i");
string flag;
string::size_type position;
//find 函数 返回jk 在s 中的下标位置
position = s.find("jk");
if (position != s.npos) //如果没找到,返回一个特别的标志c++中用npos表示,我这里npos取值是4294967295,
{
printf("position is : %d\n" ,position);
}
else
{
printf("Not found the flag\n");
}
}
2.返回子串出现在母串中的首次出现的位置,和最后一次出现的位置。
② find_first_of()
函数原型:int find_first_of(char c, int start = 0);
这个用法和①中str1.find(str2)相似,都是返回str2中首个字符在str1中的地址。
但是要特别注意,没有找到时返回值是-1.
③ find_last_of()
函数原型:int find_last_of(char c);
未找到时返回-1。
④ find_not_first_of()
函数原型:size_type find_first_not_of( char ch, size_type index = 0 );
在字符串中查找第一个与str中的字符都不匹配的字符,返回它的位置。搜索从index开始。如果没找到就返回string::nops。
⑤ find_not_last_of()
函数原型:size_type find_last_not_of( char ch, size_type index = 0 );
在字符串中查找最后一个与str中的字符都不匹配的字符,返回它的位置。搜索从index开始。如果没找到就返回string::nops。
position = s.find_first_of(flag);
printf("s.find_first_of(flag) is :%d\n",position);
position = s.find_last_of(flag);
printf("s.find_last_of(flag) is :%d\n",position);
结果:
3.查找某一给定位置后的子串的位置
//从字符串s 下标5开始,查找字符串b ,返回b 在s 中的下标
position=s.find("b",5);
cout<<"s.find(b,5) is : "<<position<<endl;
4.查找所有子串在母串中出现的位置
//查找s 中flag 出现的所有位置。
flag="a";
position=0;
int i=1;
while((position=s.find(flag,position))!=string::npos)
{
cout<<"position "<<i<<" : "<<position<<endl;
position++;
i++;
}
5.反向查找子串在母串中出现的位置,通常我们可以这样来使用,当正向查找与反向查找得到的位置不相同说明子串不唯一。
//反向查找,flag 在s 中最后出现的位置
flag="3";
position=s.rfind (flag);
printf("s.rfind (flag) :%d\n",position);