string的find( )函数✅

1. 基本用法

语法

string的find()函数用于找出字母在字符串中的位置。

find(str,position)
  • str:是要找的元素

  • position:字符串中的某个位置,表示从从这个位置开始的字符串中找指定元素(不填第二个参数,默认从字符串的开头进行查找)

返回值为目标字符的位置(第一个字符位置为0),当没有找到目标字符时返回npos

举例
//找到目标字符的位置
string s = "hello world!";
cout << s.find("e") << endl;
输出结果:1
//未找到目标字符
string s = "hello world!";
if (s.find("a") == s.npos) {
    cout << "not found" << endl;
}
输出结果:not found
//指定查找位置
string s = "hello world!";
cout << s.find("l",5) << endl;
输出结果:9


2. 延伸用法

2.1 找到目标字符第一次出现和最后一次出现的位置
string s = "hello world!";
cout <<s.find_first_of("l") << endl;//第一次出现的位置
cout << s.find_last_of("l") << endl;//最后一次出现的位置

结果为:
2
9

2.2 反向查找
string s = "hello world!";
cout << s.rfind("l") << endl;//即从后往前第一次出现"l"的位置

结果为:9

通常我们可以这样来使用,当正向查找与反向查找得到的位置不相同说明子串不唯一。

2.3 查找所有子串在母串中出现的位置
//查找s 中flag 出现的所有位置。
	string s("hello world!");
    string flag="l";
    int position=0;
    int i=1;
    while((position=s.find(flag,position))!=string::npos)
    {
        cout<<"position  "<<i<<" : "<<position<<endl;
        position++;
        i++;
    }

运行结果

  position  1 : 2
  position  2 : 3
  position  3 : 9
  • 48
    点赞
  • 227
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值