比较两个字符串,寻找它们最大的公共子串:
#include <iostream>
char* CommonStr(const char* str1, const char* str2)
{
const char *longStr;
const char *shortStr;
if (str1 == NULL || str2 == NULL) return NULL;
int len1 = strlen(str1);
int len2 = strlen(str2);
if (len1 <= len2)
{
longStr = str2;
shortStr = str1;
}
else
{
longStr = str1;
shortStr = str2;
}
char* sub = new char[strlen(shortStr) + 1];
if (strstr(longStr, shortStr))
{
strcpy_s(sub,strlen(shortStr), shortStr);
sub[strlen(shortStr)] = '\0';
return sub;
}
len1 = strlen(shortStr);
len2 = strlen(longStr);
int len3 = len1;
while (len3--)
{
for (int i = 0; i < len1 - len3; i++)
{
memcpy(sub, shortStr + i, len3);
sub[len3] = '\0';
if (strstr(longStr, sub))
{
return sub;
}
}
}
return NULL;
}
int main()
{
char str1[] = " hello world";
char str2[] = "lo hhhh";
char* sub = CommonStr(str1, str2);
std::cout << sub;
delete[] sub;
system("PAUSE ");
}