分别输入两个字符串,查找最长的部分,以下是代码,刚刚写完,新手,拍砖轻点哦。
之前写过,主要使用的是goto语句,后来听大家意见改成用while语句,以下是代码,希望大家给点意见,算法,麻不麻烦,可读性等等各方面,目的是希望能提高自己写程序的规范以及掌握一些解决问题的基本方法,谢谢了
#include<iostream>using namespace std;void handle(char a[],char b[],int c[]){ int i=0,j=0; //a[],b[]的下标 int flag_i,flag_j; //a[],b[]的下标 int count=0; //记录有多少公共部分 int flag=0; //记录代码是否执行//以b[]为基准寻找和a[]有多少公共部分 while(b[j]!='\0') { while(a[i]!='\0') { if(a[i]==b[j]) {flag_i=i; flag_j=j; while(a[flag_i]==b[flag_j]&&a[flag_i]!='\0'&&b[flag_j]!='\0') { ++flag_i; ++flag_j; ++count; } } else ++i,flag=1; if(count>c[0]) c[0]=count, c[1]=j; if(a[i]=='\0') break; if(flag==0) ++i; flag=0; count=0; }; ++j; i=0; };}void output(char b[],int c[]){ if(c[0]==0) cout <<"there is not the similar part." <<endl; else {cout <<"The same string are ("; for(int i=c[1];i<c[0]+c[1];++i) cout <<b[i]; cout <<")."<<endl; };}int main(){ cout <<"Enter two string:"<<endl; char a[30]; cout <<"The fisrt is:"; gets(a); cout <<"The scend is:"; char b[30]; gets(b);//使其返回有多少个公共部分,起始位置在哪 int c[2]={0}; handle(a,b,c); output(b,c); return 0;}