我试图找到2个字符串之间的最大重叠并打印2个字符串,重叠只在新创建的字符串中出现一次。
#include<stdio.h>
#include<string.h>
int main(void)
{
char string1[64],string2[64];
char s3[128];
int len=0;
printf("Enter string1");
scanf("%s",string1);
printf("Enter string2");
scanf("%s",string2);
for (char* s1 = string1; *s1 != '\0'; ++s1)
{
int overlap = 0;
for (char* s2 = string2; *s2 != '\0'; ++s2)
{
while (s1[overlap] != '\0' && s1[overlap] == s2[overlap])
{
++overlap;
}
if ( len < overlap )
{
len = overlap;
}
}
s3[overlap]=string1[overlap];
}
printf("%d\n",len);
printf("%s\n",s3);
printf(strcat(string1,string2));
return 0;
}
我找到了最大重叠和重叠中的那些字符,但我不知道如何从2个字符串的组合中减去重叠来得到我的答案。示例:a123和a123457应该给我4和a123457(a123只出现一次)。
答案 0 :(得分:0)
事实证明这比我预期的要多。我将你的指针转换为整数索引,以便可以直接比较两个字符串(构造新字符串所必需的。)然后我添加了变量来跟踪每个字符串中最长重叠的开始:
#include <stdio.h>
#include <string.h>
#define MAX_STR_LEN (64)
int main(void) {
char string1[MAX_STR_LEN], string2[MAX_STR_LEN], string3[MAX_STR_LEN * 2 - 1];
int longest_overlap = 0, overlap_offset_s1 = -1, overlap_offset_s2 = -1;
printf("Enter string1: ");
scanf("%s", string1);
printf("Enter string2: ");
scanf("%s", string2);
int s1_len = strlen(string1), s2_len = strlen(string2);
for (int s1 = 0; s1 < s1_len; s1++)
{
for (int s2 = 0; s2 < s2_len; s2++)
{
int overlap = 0;
while (s1 + overlap < s1_len && s2 + overlap < s2_len && string1[s1 + overlap] == string2[s2 + overlap])
{
++overlap;
}
if (longest_overlap < overlap)
{
longest_overlap = overlap;
overlap_offset_s1 = s1;
overlap_offset_s2 = s2;
}
}
}
printf("%d\n", longest_overlap);
strncpy(string3, &string1[overlap_offset_s1], longest_overlap);
string3[longest_overlap] = '\0';
printf("%s\n", string3);
if (longest_overlap == 0)
{
strcat(strcpy(string3, string1), string2);
}
else if (overlap_offset_s1 > overlap_offset_s2 || (overlap_offset_s1 == overlap_offset_s2 && s1_len < s2_len))
{
strcpy(string3, string1);
string3[overlap_offset_s1] = '\0';
strcat(string3, &string2[overlap_offset_s2]);
}
else
{
strcpy(string3, string2);
string3[overlap_offset_s2] = '\0';
strcat(string3, &string1[overlap_offset_s1]);
}
printf("%s\n", string3);
return 0;
}
<强>实施例强>
> ./a.out
Enter string1: a123
Enter string2: a123457
4
a123
a123457
>
> ./a.out
Enter string1: abcdef
Enter string2: cdefgh
4
cdef
abcdefgh
>
> ./a.out
Enter string1: cdefgh
Enter string2: abcdef
4
cdef
abcdefgh
>
其他示例
> ./a.out
Enter string1: abc
Enter string2: 123
0
abc123
>