【发布时间】:2020-08-01 17:32:26
【问题描述】:
我有一个函数,它接受两个字符串并返回,没有双精度, 出现在两个字符串中的字符,按照它们出现在第一个字符串中的顺序 一。 这是我在 C 中的实现:
#include <string.h>
//Remove all char duplicates in string
//Sub function
char *removeAll(char* str,char c, int pos)
{
int i,j;
int len = strlen(str);
for (i = pos+1;i<len;i++)
{
if (str[i] == c)
{
for (j=i;j<len;j++)
{
str[j] = str[j+1];
}
len--;i--;
}
}
return str;
}
//Finds all common chars and concatenate it to one string
//Sub function
char* commonString(char* p1,char* p2)
{
char* res = "";
for (int k=0;k<strlen(p1);k++)
{
for (int h=0;h<strlen(p2);h++)
{
if (p1[k] == p2[h])
{
strcat(res,&p1[k]);
}
}
}
return res;
}
/* The main function that takes two strings and return, without doubles, the
characters that appear in both strings, in the order they appear in the first
one.*/
char* inter(char* s1,char* s2)
{
char* new_str,*new_str1;
int len1 = strlen(s1),len2 = strlen(s2);
for (int i = 0;i<len1;i++)
{
new_str = removeAll(s1, s1[i], i);
len1 = len1-(len1-strlen(new_str));
if (strcmp(new_str, s1) != 0) i = 0;
}
for (int j = 0;j<len2;j++)
{
new_str1 = removeAll(s2, s2[j], j);
len2 = len2-(len2-strlen(new_str1));
if (strcmp(new_str1, s2) != 0) j = 0;
}
char* res = commonString(new_str, new_str1);
return res;
}
它给出“FAILURE EXECUTION” 我的代码有什么问题?你能帮忙解决这个问题吗?
I/O 示例:
示例 00
> Input: "padinton" && "paqefwtdjetyiytjneytjoeyjnejeyj"
> Output:
> Return Value: "padinto"
示例 01
> Input: "ddf6vewg64f" && "gtwthgdwthdwfteewhrtag6h4ffdhsd"
> Output:
> Return Value: "df6ewg4"
示例 02
> Input: "nothing" && "This sentence hides nothing"
> Output:
> Return Value: "nothig"
【问题讨论】:
-
main 函数在哪里?
-
老实说,这是来自特定平台(站点)的任务。所以我只需要写一个函数。你能评论一下吗?
-
请看我的回答,解释从执行失败开始的一些问题,反正我没有解决所有问题,因为其他问题是另一个问题
-
当然,我已经在我自己的代码中修复了字符串比较问题。谢谢。现在我只需要解决“常见字符串”问题。