从前面用两个for语句扫描字符串,然后分别从前面和后面查找截取的字符串,判断他们的位置是否一样
#include <iostream>
#include <string>
using namespace std;
void main(){
string str = "yyabcdabcdabjcabceg",strmax="";
int len = str.length();
int max= 0,index=0;
for(int pos1 = 0; pos1 < len; pos1++)
for(int pos2 = pos1 + 1; pos2 < len; pos2++){ //substr截取从POS1开始的pos2-pos1+1个字符串
string tep=str.substr(pos1,pos2-pos1+1);//截取1和2之间的字符串
int t=str.find(tep);//查找tep首次出现的位置
int num=str.rfind(tep);//从字符串倒序查找tep位置
if(t!=num&&num>pos2&&tep.length()>max){//比较查找是否一致和字符串大小是否大于max
//这里一定要检测后一个字符串位置num大于前一个字符串的最后一个字符,防止abcdabcda这种情况输出5
strmax=tep;
max=tep.length();
index=pos1+1;
}
}
cout << strmax << "," << index << endl;
}