代码不适用于长回文

标签 c palindrome

我正在处理一项作业,我必须从用户那里获取句子输入,以相反的顺序打印单词,检查字谜和回文。我得到了一个用于字谜的函数,而且我几乎让我的回文函数起作用了。现在,我只要求两个词,这样我就可以让我的功能正常工作。然而,出于某种原因,每当我为我要求的两个词输入一个冗长的回文(例如,racecar 或 detartrated 与 Mom 或 Dad 相比)时,回文函数就会变得困惑。

这是代码;

#include <stdio.h>
#include <ctype.h> //Included ctype for tolower / toupper functions
#define bool int
#define true 1
#define false 0

//Write boolean function that will check if a word is a palindrome
bool palindrome(char a[])
{
    int c=0;
    char d[80];
    //Convert array into all lower case letters
    while (a[c])
    {
        a[c] = (tolower(a[c]));
        c++;
    }
    c = 0;

    //Read array from end to beginning, store it into another array
    while (a[c])
        c++;

    while(a[c] != 0 && c > -1)
    {
        d[c] = a[c];
        c--;
    }

    c = 0;

    while(a[c])
    {
        printf("%c", d[c]);
        printf("%c", a[c]);
        c++;
    }
    //If two arrays are equal, then they are palindromes
    for(c = 0; a[c] && d[c]; c++)
    {
        while(a[c] && d[c])
        {
        if(a[c] != d[c])
            return false;
        }
    }
    return true;
}

int main(void)
{
    char a[80], b[80];
    bool flagp;
    //Prompt user to enter sentence
    printf("Enter a word: ");
    gets(a);

    flagp = palindrome(a);

    if (flagp)
    {
        printf("\nThe word is a palindrome.");
    }
    else
    {
        printf("\nThe word is not a palindrome.");
    }

    return 0;
}

它输出这个;

Enter first word: racecar
_r▬a↨c e c a r
The word is not a palindrome.

但是,如果我输入“racecar”,它会错误地指出它不是回文。

请告诉我我做错了什么:'(

最佳答案

  1. 所以 a[c] != d[c] 在您期望它为假时为真。
  2. 您已经用 printf 证明这是因为 d[c] 是垃圾。
  3. 这意味着 d 不包含 a 的反转。
  4. 因此,这导致人们检查以下代码段:

    while(a[c] != 0 && c > -1)
    {
        d[c] = a[c];
        c--;
    }
    

    它正在尝试创建一个反向副本,但很明显它无法反向任何东西,因为它放入的索引与获取的索引相同。

(前三步你都做了,为什么到此为止?)

老实说,d 根本就没有存在的理由。这一切都可以就地完成。

   +---+---+---+---+---+---+---+
a: | r | a | c | e | c | a | r |
   +---+---+---+---+---+---+---+
     ^                       ^
     |   compare these two   |


         ^               ^
         |  then these   |


                ...

所以代码看起来像这样:

size_t len = strlen(a);
if (len) {
   size_t i = 0;
   size_t j = len - 1;
   while (i < j) {
      if (a[i++] != a[j--])
         return 0;
   }
}

return 1;

注意事项:

  1. 请不要执行#define true 1#define false 0。这些不同于 C 的定义,因此如果您执行 if (b == true) 而不是 if (b),您可能会得到错误的结果。

    <
  2. c 通常表示一个chari(以及 jk)更常用于索引。

关于代码不适用于长回文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19340153/

相关文章:

c - 在 C 中只打印一次

c - linux回文字符串参数

c - 为什么我的回文函数不起作用?

c - gethostbyname() 返回具有负地址的结构

c - RegEnumValue 和 REG_MULTI_SZ 类型

c - 如何修复 `itoa` 实现,使其不打印反向输出?

python - 最长回文子串自顶向下动态规划

c - 为什么字符串不相等?

记录 R 中循环的输出

c - C有模板吗?