1. 程式人生 > >C++字串查詢方法

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

結果
在這裡插入圖片描述