C字符数组比较

时间:2019-05-08 16:44:42

标签: c

好吧,所以我在codewars.com上进行了编码挑战,挑战是将一个字符串作为输入并返回一个字符串,在该字符串中,代替字母的是与该字母匹配的字母的数字。

除了字母之外的所有内容都将被忽略。

ex:“ aab”将返回“ 1 1 2”

每个数字之间应有一个空格,代表字母中的一个字母。

因此,当我在IDE(使用c99使用xcode)上运行此代码时,一切看起来都很好,并且strcmp()函数说两个字符串相等。 我相信我使用的网站使用C11,但我看不到会导致错误的原因。

当我在挑战网站上运行此代码时,它通过了几次测试,但随后也失败了。当输入字符串为“”时,它失败,并且在下面的代码中使用的字符串中,它也失败,但是在我的ide上运行它时,它也不会失败。

我的问题是:

1)知道导致此错误的原因是什么吗?

2)就代码而言,您会做些什么

谢谢

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

char *alphabet_position(char *text)
{
    int i,letter_position;
    unsigned long int size = strlen(text);

    char *result = malloc(sizeof(int)*size + 1);

    char int_string[10];
    char temp = ' ';

    //If String wasn't blank
    if (strcmp(text, "")!=0)
    {
        for (i=0; i<size-1; i++)
        {
            //If it is a letter
            if (isalpha(text[i]))
            {
                temp = tolower(text[i]);
                if (temp == 'a')
                    strcat(result, "1");
                else
                {
                    letter_position = temp - 'a' + 1;
                    sprintf(int_string,"%d",letter_position);
                    strcat(result, int_string);
                }
                //Print space after letter until the last letter
                if (i!=size-2)
                    strcat(result, " ");
            }
        }
        strcat(result, "\0");
        return result;
    }
    else
    {
        strcat(result, "\0");
        return result;
    }

}


int main(void)
{

    char *string = alphabet_position("The narwhal bacons at midnight.");
    char *expected_output = "20 8 5 14 1 18 23 8 1 12 2 1 3 15 14 19 1 20 13 9 4 14 9 7 8 20";

    printf("Your output %s\n", alphabet_position("The narwhal bacons at midnight."));
    printf("Expt output %s\n", "20 8 5 14 1 18 23 8 1 12 2 1 3 15 14 19 1 20 13 9 4 14 9 7 8 20");

    printf("\n");

    printf("your len %lu\n", strlen(alphabet_position("The narwhal bacons at midnight.")));
    printf("Expt len %lu\n", strlen(expected_output));

    if (strcmp(string, expected_output)==0)
        printf("Equal\n");
    else
        printf("Not equal\n");
    return 0;
}

1 个答案:

答案 0 :(得分:4)

您有两个严重的问题。

首先,您没有将result数组的内容初始化为一个空字符串。致电malloc()后,添加:

result[0] = '\0';

malloc()不会初始化它分配的内存。还有另一个函数calloc(),它使用略有不同的参数并将内存初始化为零。但是您只需要第一个字符为零,因此就不需要了。

第二,for循环未处理text的最后一个字符。应该是:

for (i = 0; i < size; i++)

类似地,是否添加空格的测试应为if (i != size-1)。您是否认为strlen()在末尾算空字符?

您在malloc()中指定的空间量不正确,但实际上不会造成问题。 sizeof(int)与显示整数值所需的字符数无关。由于您只是打印字母位置,因此最多为26,因此每个输入字符需要3个字符。因此,应该是:

char *result = malloc(3 * size + 1);

您的分配之所以有效,是因为sizeof(int)通常至少为4,因此您分配的空间已绰绰有余。

还有其他一些小问题不会影响结果的正确性:

您不需要专门处理if的{​​{1}}语句,'a'中的代码将适用于所有字母。

您最后不需要elsestrcat(result, "\0")必须已经为null终止,以便您将其用作result的参数,因此使用strcat()添加null终止符没有意义。

相关问题