【问题标题】:I wrote a function that takes two strings and returns, without doubles, common chars. What's wrong with it?我写了一个函数,它接受两个字符串并返回普通字符,没有双精度。它出什么问题了?
【发布时间】: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 函数在哪里?
  • 老实说,这是来自特定平台(站点)的任务。所以我只需要写一个函数。你能评论一下吗?
  • 请看我的回答,解释从执行失败开始的一些问题,反正我没有解决所有问题,因为其他问题是另一个问题
  • 当然,我已经在我自己的代码中修复了字符串比较问题。谢谢。现在我只需要解决“常见字符串”问题。

标签: c string function


【解决方案1】:

你的代码有几个问题

它给出“失败执行”我的代码有什么问题?

commonString 中,您尝试修改根据定义不可修改的文字字符串,因此行为未定义:

char* res = "";
...
strcat(res,&p1[k]);

removeAll 总是返回它的第一个参数,所以在 inter

new_str = removeAll(s1, s1[i], i);
...
if (new_str != s1) i=0;

new_str1 = removeAll(s2, s2[j], j);
...
if (strcmp(new_str1, s2) != 0) j = 0;

测试总是正确的,即使这样做你比较指针并且可能你想比较它们的内容,假设它们可以不同(但当然它们不能)。要比较两个字符串的内容,请使用 strcmp

【讨论】:

  • 详细信息:“根据定义不可修改的文字字符串”更像是尝试修改字符串文字的未定义行为。它可能起作用。 IAC,好的代码不会尝试修改。
  • @chux-ReinstateMonica 你是对的,我是对的。该代码有很多问题可能对我来说最好不要开始看它^^
猜你喜欢
  • 2020-11-24
  • 2022-11-15
  • 1970-01-01
  • 2022-12-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多