C++字符串查找方法

find_first_of

这个函数的查找是针对单个字符的匹配,对于字串中的每个字符,只要父串的该字符匹配到字串中任意一个字符,就算成功,first则说明是从左往右返回匹配成功的第一个。

测试代码

    #include <iostream>
    using namespace std;
    
    int main(){
    	string s1="i want to have a car.";
    	string s2="aeiou";
    	size_t found=s1.find_first_of(s2);
    	while(found!=string::npos){
    		s1[found]='*';
    		found=s1.find_first_of(s2,found+1);
    	}
    	cout<<s1;
    	return 0;
    }

结果
在这里插入图片描述

find_first_not_of

和find_first_of逻辑相反,当子串中的任意一个字符和父串的字符都不匹配时,我们返回它的第一个该字符的位置

测试代码

#include <iostream>
using namespace std;

int main(){
	string s1="i want to have a car.";
	string s2="aeiou";
	size_t found=s1.find_first_not_of(s2);
	while(found!=string::npos){
		s1[found]='*';
		cout<<s1<<endl;
		found=s1.find_first_not_of(s2,found+1);
	}
	return 0;
}

结果
在这里插入图片描述

find_last_of

和find_first_of作用相同,找到匹配的字符,不过find_first_of是从前往后找,但是它是从后往前找,返回的都是第一个匹配成功的位置。

测试代码

#include <iostream>
using namespace std;

int main(){
	string s1="i want to have a car.";
	string s2="aeiou";
	size_t found=s1.find_last_of(s2);
	while(found!=string::npos){
		s1[found]='*';
		cout<<s1<<endl;
		found=s1.find_last_of(s2,found-1);  //注意,这是found位置是-1
	}
	return 0;
}

结果
在这里插入图片描述

find_last_not_of类比之前的find_first_not_of.

find

之前的匹配都是针对单个字符的匹配,find是针对字符串的全字匹配。

测试代码

#include <iostream>
using namespace std;

int main(){
	string s1="i want to have a car.";
	string s2="want";
	string s3="wans";
	size_t pos=s1.find(s2);
	size_t pos1=s1.find(s3);
	if(pos!=string::npos){
		cout<<"string found"<<endl;
	}
	else
		cout<<"not found"<<endl;
	if(pos1!=string::npos){
		cout<<"string found"<<endl;
	}
	else
		cout<<"not found"<<endl;
	return 0;
}

结果
在这里插入图片描述

  • 9
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值