C++ string 找出字元第n次出現的位置
阿新 • • 發佈:2021-01-17
技術標籤:C++
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
/*
T:要搜尋的串
P:要匹配的串
*/
int pos(string T, string P, int n){
if(n==0)return -1;//相當於沒找
int count = 0;
unsigned begined = 0;
while((begined=T.find(P,begined))!=string::npos){
count++;
begined + = P.length();
if(n==count){
return begined-1;
}
}
return -2;//意味著沒有那麼多次
}
int main(){
int n = 2;
string str1 = "mamad";
string str2 = "m";
cout<<str2<<" 第 "<<n<<" 次出現的位置是 "<<pos(str1, str2, n)<<endl;
return 0;
}