2007年5月20日星期日

蛮力法查找字符串

/*

在字符串str中查找字符串p出现过的次数及位置

要点:蛮力法

*/



#include <iostream>

#include <string>

using namespace std;

void main(){

int i=0,j=0,count=0;

string str="我爱你中华人民共和国";

string p="中国";

int m=str.length();

int n=p.length();

if (n>m) {

cout<<"没有找到您需要的字符串!您输入的字符串过长!"<<endl;exit(0);

}

for(i=0;i<=m-n;j=0,i++){//进行下一轮查找时,j必须归零

while((p[j]==str[i+j])&&j<n)

j=j+1;

if(j==n){count++;

cout<<"第"<<count<<"个匹配字符串起始在第"<<i<<"个位置"<<endl;

}



}

if(count==0) cout<<"没有找到您需要的字符串"<<endl;









}


相关文章