本文实例讲述了C语言求两个字符串的最长公共子串的方法。分享给大家供大家参考。具体实现方法如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
|
#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语言程序设计有所帮助。