C++字符串的查找

关于字符串的各种查找

原文出处:https://www.cnblogs.com/yongpan/p/7920165.html

 

1 find函数:在字符串中查找子字符串中出现的位置

  1. 函数最终返回的是子字符串出现在字符串中的起始下标
  2. 该函数有两个参数,第一个参数是待查找的子字符串
  3. 第二个参数是表示开始查找的位置(默认从0开始查找)
#include <iostream>
#include <string>
using namespace std;

int main() {
	string s1 = "first second third";
	string s2 = "second";
	int index = s1.find(s2,0);
	if(index < s1.length())
		cout<<"Found at index : "<< index <<endl;
	else
		cout<<"Not found"<<endl;
	return 0;
}

 输出结果为:Found at index : 6

 

rfind函数:在字符串中查找子字符串

  1. 与find函数不同的是最多查找到第二个参数处
  2. 如果到了第二个参数所指定的下标还没有找到子字符串,则返回一个无穷大值
#include <iostream>
#include <string>
using namespace std;

int main()
{
    string s1 = "first second third";
    string s2 = "second";
    int index = s1.rfind(s2,6);
    if(index < s1.length())
        cout<<"Found at index : "<< index <<endl;
    else
        cout<<"Not found"<<endl;
    return 0;
}

 输出结果为:Found at index : 6

 

find_first_of函数:查找子字符串和字符串共同具有的字符在字符串中出现的位置

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string s1 = "first second second third";
    string s2 = "asecond";
    int index = s1.find_first_of(s2);
    if(index < s1.length())
        cout<<"Found at index : "<< index <<endl;
    else
        cout<<"Not found"<<endl;
    return 0;
}

4 find_first_not_of函数:查找在s1字符串但不在s2字符串中的首位字符的下标

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string s1 = "secondasecondthird";
    string s2 = "asecond";
    int index = s1.find_first_not_of(s2);
    if(index < s1.length())
        cout<<"Found at index : "<< index <<endl;
    else
        cout<<"Not found"<<endl;
    return 0;
}

 

  • 3
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值