【C++学习纪录】string容器——查找

1、int find(const string &str, int pos = 0) const 查找str第一次出现位置,从pos开始查找
2、int find(const char *s, int pos = 0) const 查找s第一次出现位置,从pos开始查找
3、int find(const char *s, int pos, int n) const 从pos位置查找s的前n个字符第一次位置
4、int find(const char c, int pos = 0) const 从pos位置查找字符c第一次位置
5、int rfind(const string &str, int pos = npos) const 查找str位置,从pos开始查找(从右往左查找)
6、int rfind(const char *s, int pos = npos) const 查找s出现位置,从pos开始查找(从右往左查找)
7、int rfind(const char *s, int pos, int n) const 从pos开始查找s前n个字符位置(从右往左查找)
8、int rfind(const char c, int pos = 0) const 查找字符c出现位置(从右往左查找)

一、int find(const string &str, int pos = 0) const 查找str第一次出现位置,从pos开始查找

#include<iostream>
#include<string>
using namespace std;
int main()
{
    string temp = "abc";
    string str = "defabcghi";
    cout << str.find(temp, 0) << endl;
    system("pause");
}

运行结果:
可以看出string字符串起始元素的的下标是0。不论开始查找的位置是几,返回的结果依旧是以0为基准。

3
请按任意键继续. . .

二、int find(const char *s, int pos = 0) const 查找s第一次出现位置,从pos开始查找

三、int rfind(const string &str, int pos = npos) const 查找str最后一个位置,从pos开始查找
(从右边开始找)

#include<iostream>
#include<string>
using namespace std;
int main()
{
    string temp = "abc";
    string str = "abcdefabcghi";
    //第二个参数应该是从右往左开始的起始位置
    cout << str.rfind(temp, 12) << endl;
    system("pause");
}

运行结果:
虽然是从右往左查找,但返回的结果依旧是以0为基准,要查找的字符串首元素的位置

6
请按任意键继续. . .

四、int rfind(const char *s, int pos = npos) const 查找s出现位置,从pos开始查找(从右往左找)

五、int find(const char *s, int pos, int n) const 从pos位置查找s的前n个字符第一次位置

#include<iostream>
#include<string>
using namespace std;
int main()
{
    char *temp = "abc123";
    string str = "abcdefabcghi";
    cout << str.find(temp, 4, 3) << endl;
    system("pause");
}

运行结果:

6
请按任意键继续. . .
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值