本文執行個體講述了C語言求兩個字串的最長公用子串的方法。分享給大家供大家參考。具體實現方法如下:
#include "stdio.h"#include "string.h"#include "stdlib.h"void getCommon(char str1[],char str2[],char * str3);int stringLength(char * str);void main(){char str1[50];char str2[50];char str3[50];gets(str1);gets(str2);getCommon(str1,str2,str3);printf("%s\n",str3);// printf("%d\n",stringLength(str2));}int stringLength(char * str){int len = 0;while(*str != '\0'){len++;str++;}return len;}void getCommon(char str1[],char str2[],char * str3){int len1,len2;int i,j,k;int max=0;int start = -1;len1 = stringLength(str1);len2 = stringLength(str2);for(i = 0; i < len1; i++){for(j = 0; j < len2; j++){if(str1[i] == str2[j]){for(k = 0; (str1[i+k] == str2[j+k] && str1[i+k] != '\0'); k++);if(max < k){max = k;start = i;}}}}if(start == -1){str3[0] = '\0';;}else{memcpy(str3,&str1[start],max);str3[max] = '\0';}}
希望本文所述對大家的C語言程式設計有所協助。