1. 程式人生 > >C++中find函式用法

C++中find函式用法

C++中STL裡提供了許多字串操作的函式,下面是字串查詢方面的部分函式用法簡介:

1.find()

查詢第一次出現的目標字串:

#include<iostream>

#include<csdtio>

using namespace std;

int main(){

string s1 = "abcdef";

string s2 = "de";

int ans = s1.find(s2) ;   //在S1中查詢子串S2

cout<<ans<<endl;

system("pause");

}

說明:如果查詢成功則輸出查詢到的第一個位置,否則返回-1;

查詢從指定位置開始的第一次出現的目標字串:

#include<iostream>

#include<csdtio>

using namespace std;


int main(){

string s1 = "abcdef";

string s2 = "de";

int ans = s1.find(s2, 2) ;   //從S1的第二個字元開始查詢子串S2

cout<<ans<<endl;

system("pause");

}


2.find_first_of()

查詢子串中的某個字元最先出現的位置。find_first_of()不是全匹配,而find()是全匹配

#include<iostream>

#include<csdtio>

using namespace std;

int main(){

string s1 = "adedef";

string s2 = "dek";

int ans = s1.find_first_of(s2) ;   //在S1中查詢子串S2

cout<<ans<<endl;

system("pause");

}

其中find_first_of()也可以約定初始查詢的位置:s1.find_first_of(s2, 2) ;

3.find_last_of()

這個函式與find_first_of()功能差不多,只不過find_first_of()是從字串的前面往後面搜尋,而find_last_of()是從字串的後面往前面搜尋。

4.rfind()

反向查詢字串,即找到最後一個與子串匹配的位置

5.find_first_not_of()

找到第一個不與子串匹配的位置