c - C 中的回文

标签 c

我正在编写回文代码来检查给定的字符串是否是回文。例如:妈妈,1001...

MY_CODE:

#include <stdio.h>
#include <stdlib.h>
#include <stdio_ext.h>

int main()
{
  int i,n;
  char p[999];
  char flag;   

printf("number of characters in the strings");
scanf("%d",&n);
printf("Enter string: ");  
for (i=0;i<n;i++)
{
    printf("\n");
    __fpurge(stdin);
    scanf("%c",&p[i]);
}

for (i=0;i<n;i++)
{
    if (p[i]==p[n-1-i])
    {
        flag=0;
        break;
    }
    else flag=1;
}
if (flag==1)
    printf("It's not a palindrome");
if (flag==0)
    printf("It's a palindrome.");
return 0;
}

我试图这样做的想法是,如果最后一个和第一个字符匹配,对于下一个字符依此类推。如果它们全部匹配,则字符串是回文,否则不是,就这么简单,但我的输出 显示 123;妈妈;每一个废话都是一个回文(“甚至是‘废话’这个词:D)。

有人可以指导我吗?

P.S.:我是一个新手,正在学习 C。我的操作系统:Ubuntu 15.10。

最佳答案

您正在检查字符是否相同,设置 flag=0 表示它是回文,但这会发生在第一个匹配中 - 如果其他匹配没有发生,则该标志永远不会设置为不是一个回文。

更好的方法是假设它是回文,然后如果有其他情况,将其设置为 false。

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

int main()
{
  char p[999];

  printf("Enter string: ");
  if(fgets(p, sizeof(p), stdin))
  {
    int palindrome = 1;
    int i;
    int n;

    n = strlen(p);

    /* handle new line at end of fgets input */
    if(p[n-1] == '\n')
      p[n-1] = '\0';
    n = strlen(p);

    /* 0 length string (after newline removed) - not a palindrome */
    if(n == 0) palindrome = 0;

    for(i=0;i<n/2;i++)
    {
      /* look for a chatacter pair that doesn't match - if find, then we don't have a palindrome */
      if(p[i] != p[n-1-i])
        palindrome = 0;
    }
    if(palindrome)
      printf("is a palindrome\n");
    else
      printf("is not a palindrome\n");
  }
  return 0;
}

关于c - C 中的回文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38059418/

相关文章:

c - 在输入行中间使用 EOF?

c - sqrt() 函数不适用于可变参数

c - 没有声音。通过 RubyDL 使用 Ruby 和 winmm

c++ - 编译时如何更改makefile诊断消息[GNU ARM GCC,Eclipse make.exe]

c - 使用 RSA_private_decrypt() 解密二进制文件

c - 如果我在 FFmpeg 中使用 av_read_frame 会丢失多个帧

c - 是否有任何现有的 C 实现在(无)符号整数表示中具有填充位?

编译.C 文件 : Undefined symbols for architecture x86_64

c - 在Mac控制台中同时运行2个C程序

javascript - 将 Node Chat 服务器与 ChucK 链接以获得声音