我在C程序中做错了什么来检查一个字符串是Palindrome还是没有?

问题描述 投票:-1回答:2

以下是我编写的C程序,用于检查输入字符串是否为Palindrome,但它始终显示'else'语句,即字符串不是Palindrome: -

#include<stdio.h>
#include<string.h>
void main()
{
int i,n,count=0;
char f[30];
printf("Enter the string. :  ");
gets(f);
n = strlen(f);

for(i=0;i<n;i++)
{
    if(f[i+1]==f[n-i])
    count=count+1;
}
if(count==n)
printf("\n Entered string is Palindrome");
else
printf("\n Entered string is NOT Palindrome");

}
c palindrome
2个回答
0
投票

i = 0时,f[n-i]将是终止空字符,它将永远不会出现在字符串的中间。因此,如果字符串长度为2-char或更长,则条件f[i+1]==f[n-i]将为false。 (如果字符串长度为1-char,则f[i+1]将是第一个(也是唯一)字符后的终止空字符,因此条件为真。)

条件应该是f[i]==f[n-i-1]

顺便说说,

  • 您不应该使用具有不可避免的缓冲区溢出风险的gets(),在C99中弃用并从C11中删除。
  • 你应该在托管环境中使用标准的int main(void)而不是void main(),这在C89中是非法的,在C99或更高版本中是实现定义的,除非你有一些特殊的理由使用这个非标准签名(例如,被迫从你的老板那里使用它)或老师)。

完整固定代码的示例:

#include<stdio.h>
#include<string.h>
int main(void)
{
    int i,n,count=0;
    char f[30 + 1]; /* allocate one more element for storeing newline character */
    char* lf;
    printf("Enter the string. :  ");
    fgets(f, sizeof(f), stdin); /* change gets() to fgets() */
    /* fgets() stores newline character while gets() doesn't, so remove it */
    if ((lf = strchr(f, '\n')) != NULL) *lf = '\0';
    n = strlen(f);

    for(i=0;i<n;i++)
    {
        if(f[i]==f[n-i-1])
        count=count+1;
    }
    if(count==n)
        printf("\n Entered string is Palindrome");
    else
        printf("\n Entered string is NOT Palindrome");

}

0
投票

我认为只是字符串中的索引是错误的。将其从i + 1更改为i和n-i-2

#include<stdio.h>
#include<string.h>
void main()
{
    int i,n,count=0;
    char f[30];
    printf("Enter the string. :  ");
    fgets(f, 29, stdin);
    n = strlen(f);

    for(i=0;i<n;i++)
    {
        if(f[i]==f[n-i-2])
        count=count+1;
    }
    if(count==n)
    printf("\n Entered string is Palindrome");
    else
    printf("\n Entered string is NOT Palindrome");

}

另一个更有效的应该是:

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

void main()
{
    int i = 0,n,count=0;
    char f[30];
    printf("Enter the string. :  ");
    fgets(f, 29, stdin);
    n = strlen(f);

    while (i < n >> 1) {
        if (f[i]!=f[n-i-2]) {
            printf("\n Entered string is NOT Palindrome\n");
            return;
        }
        i++;
    }
    printf("\n Entered string is Palindrome\n");
    return;
}
© www.soinside.com 2019 - 2024. All rights reserved.