本文主要是介绍C++ string 找出字符第n次出现的位置,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
#include#include#includeusing 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;}
![在这里插入图片描述](/upload/202105/07/202105072227017471.png)
这篇关于C++ string 找出字符第n次出现的位置的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!