C++字符串查找方法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Gease_Gg/article/details/83860073

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;
}

结果
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/Gease_Gg/article/details/83860073