string.find()与string::npos
当判断字符串str1中是否有字符串str2时:
string str1="abcdefg";
string str2="abc";
错解1:
if(str1.find(str2)) return true; //错误的
//找不到str2会返回-1,此时if还是会执行(-1非0,满足if条件)
正解:
if(str1.find(str2) != string::npos) return true; //正确的
//默认从字符串str1下标0开始,查找字符串str2 ,返回str2在str1中的下标
cout<<str1.find(str2)<<endl;
输出:0
str1.find(str2, 5)
//从字符串str1下标5开始,查找字符串str2 ,返回str2在str1中的下标
string str1="abcdefg";
string str2="abc";
pos=str1.find(str2,5);
cout<<pos<<endl;
其他不常用find相关函数:
//find 函数 返回flag 中任意字符 在s 中第一次出现的下标位置
flag = "c";
position = s.find_first_of(flag);
cout << "s.find_first_of(flag) is : " << position << endl;
//从字符串s 下标5开始,查找字符串b ,返回b 在s 中的下标
position=s.find("b",5);
cout<<"s.find(b,5) is : "<<position<<endl;
//查找s 中flag 出现的所有位置。
flag="a";
position=0;
int i=1;
while((position=s.find_first_of(flag,position))!=string::npos)
{
//position=s.find_first_of(flag,position);
cout<<"position "<<i<<" : "<<position<<endl;
position++;
i++;
}
//查找flag 中与s 第一个不匹配的位置
flag="acb12389efgxyz789";
position=flag.find_first_not_of (s);
cout<<"flag.find_first_not_of (s) :"<<position<<endl;
//反向查找,flag 在s 中最后出现的位置
flag="3";
position=s.rfind (flag);
cout<<"s.rfind (flag) :"<<position<<endl;
}
说明:
1.
string sub = ”abc“;
string s = ”cdeabcigld“;
s.find(sub) 和s.rfind(sub) 这两个函数。当sub和s中某部分完全匹配时,才返回匹配的索引,即:当s中含有abc三个连续的字母时,才返回当前索引。
2. 如果没有查询到,则返回string::npos,这是一个很大的数,其值不需要知道。
参考前辈博客:
https://www.cnblogs.com/web100/archive/2012/12/02/cpp-string-find-npos.html
欢迎大家批评改正!!!