#include <iostream>
using namespace std;
char* GetString(char* str1, char* str2)
{
// 申请内存用于存储地址
char* SameString = new char[100];
// 初始化相同字符串长度
int update = 0;
int undate_end = 2;
// 获取字符串1的实际长度
int len_str1 = 0;
while (str1[len_str1] != '\0')
{
len_str1 += 1;
}
// 获取字符串2的实际长度
int len_str2 = 0;
while (str2[len_str2] != '\0')
{
len_str2 += 1;
}
// 循环比较获取相同字符串,遍历字符串1
for (int i = 0; i < len_str1; i++)
{
// 循环比较获取相同字符串,遍历字符串2
for (int j = 0; j < len_str2; j++)
{
// 如果存在相同的字符
if (str1[i] == str2[j])
{
// 遍历该字符之后的字符
for (int z = 0; z < len_str1 - i; z++)
{
// 若遍历的字符相同,则计数器 update + 1
if (str1[i + z] == str2[j + z])
{
update += 1;
}
else
{
break;
}
}
// 若累计的计数器超过两个字符,则获取该字符串,
// 并跳出对比循环,否则清零计数器
if (update >= undate_end)
{
for (int s = 0; s < update; s++)
{
SameString[s] = str1[i + s];
}
SameString[update] = '\0';
// 更新最大长度
undate_end = update;
update = 0;
break;
}
else
{
update = 0;
}
}
}
}
// 返回存储字符串的地址
return SameString;
}
int main()
{
// 初始化变量
char str_1[50] = "hello, my name is qianlv. ";
char str_2[20] = "what is your name?";
// 得到相同字符串的地址
char* SameString = GetString(str_1, str_2);
// 输出字符串
cout << "两个字符串的最大相同子串 = " << SameString << endl;
return 0;
}
【千律】C++基础:获取两个字符串中的最大相同子串
最新推荐文章于 2022-12-26 17:31:35 发布