string模板类的find函数的使用说明

C++函数库中的find函数是string模板类的find()系列搜索函数
例:
   string longer ("That is a funny hat.");
   
   string shorter("hat");
   
   size_type loc1=longer.find(shorter);
   
   size_type loc2=shorter.find(shorter,loc1+1);
   
   要测试查找是否失败可以采用以下语句
   
   if(loc==sring::npos)
   
   cout<<"Not found"<<endl;
1.find()
查找第一次出现的目标字符串:
#include<iostream>
#include<csdtio>
using namespace std;
int main(){
string s1 = "abcdef";
string s2 = "de";
int ans = s1.find(s2) ;   //在S1中查找子串S2
cout<<ans<<endl;
system("pause");
}

说明:如果查找成功则输出查找到的第一个位置,否则返回-1;

查找从指定位置开始的第一次出现的目标字符串:

#include<iostream>

#include<csdtio>
using namespace std;
int main(){
string s1 = "abcdef";
string s2 = "de";
int ans = s1.find(s2, 2) ;   //从S1的第二个字符开始查找子串S2
cout<<ans<<endl;
system("pause");
}
2.find_first_of()
查找子串中的某个字符最先出现的位置。find_first_of()不是全匹配,而find()是全匹配
#include<iostream>
#include<csdtio>
using namespace std;

int main(){

string s1 = "adedef";

string s2 = "dek";

int ans = s1.find_first_of(s2) ;   //在S1中查找子串S2

cout<<ans<<endl;

system("pause");

}
其中find_first_of()也可以约定初始查找的位置:s1.find_first_of(s2, 2) ;


3.find_last_of()

这个函数与find_first_of()功能差不多,只不过find_first_of()是从字符串的前面往后面搜索,而find_last_of()是从字符串的后面往前面搜索。
4.rfind()
反向查找字符串,即找到最后一个与子串匹配的位置
5.find_first_not_of()
找到第一个不与子串匹配的位置
全部评论

相关推荐

07-09 19:25
门头沟学院 Java
这是要把每一个投校招的都开盒吗?
26届之耻将大局逆转:裁人的时候一次性追回餐费
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-09 11:30
找工作7个月,投了7000封,3段世界五百强实习,才有一个offer,牛油们肯定比我强吧
码农索隆:不对不对不对,实习经历这么厉害,简历也没少投,问题出在哪呢
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务