#include <stdio.h>
#include<stdlib.h>
#include<string.h>
/*
问题:求两个字符串的最长公共子串。
要求:输入两个字符串,输出它们的最长公共子串,包括长度。
设计:
设计一个类 String,包括一个 len(字符串长度)和字符串指针 s。另有如下成员函数:
· void getstring() 从用户获取一个字符串。
· void display() 输出字符串。
· friend String maxsubstring(String str1,String str2) 友元函数,求两个字符串的最长
公共子串
*/
int main()
{
char *s1 = "woaibeijingtiananmen";
char *s2 = "welcometobeijing";
int count=0;
int count_temp=0;
char *addr=NULL;
int i = 0;
for (char *pc1 = s1; *pc1 != '\0'; pc1++)
{
for (char *pc2 = s2; *pc2 != '\0'; pc2++)
{
char *temp1 = pc1;
char *temp2 = pc2;
while ((*temp1 == *temp2) && (*temp2 != '\0'))
{
temp1++;
temp2++;
count_temp++;
}
if(count_temp>=count)///保留地址
{
addr=pc1;
count=count_temp;
}
count_temp=0;
}
}
printf("字符串子串最大长度:%d\n", count);
printf("该子串为:");
while (i < count)
{
printf("%c", addr[i]);
i++;
}
printf("\n");
system("pause");
}
#include<stdlib.h>
#include<string.h>
/*
问题:求两个字符串的最长公共子串。
要求:输入两个字符串,输出它们的最长公共子串,包括长度。
设计:
设计一个类 String,包括一个 len(字符串长度)和字符串指针 s。另有如下成员函数:
· void getstring() 从用户获取一个字符串。
· void display() 输出字符串。
· friend String maxsubstring(String str1,String str2) 友元函数,求两个字符串的最长
公共子串
*/
int main()
{
char *s1 = "woaibeijingtiananmen";
char *s2 = "welcometobeijing";
int count=0;
int count_temp=0;
char *addr=NULL;
int i = 0;
for (char *pc1 = s1; *pc1 != '\0'; pc1++)
{
for (char *pc2 = s2; *pc2 != '\0'; pc2++)
{
char *temp1 = pc1;
char *temp2 = pc2;
while ((*temp1 == *temp2) && (*temp2 != '\0'))
{
temp1++;
temp2++;
count_temp++;
}
if(count_temp>=count)///保留地址
{
addr=pc1;
count=count_temp;
}
count_temp=0;
}
}
printf("字符串子串最大长度:%d\n", count);
printf("该子串为:");
while (i < count)
{
printf("%c", addr[i]);
i++;
}
printf("\n");
system("pause");
}