Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
382 views
in Technique[技术] by (71.8m points)

c - to find if a given string is palindrome or is not palindrome

I made a program to find if a entered string is palindrome or not palindrome but it always says that its not a palindrome

#include <conio.h> 
#include <graphics.h> 
#include <string.h>
void main(void)
{
    int i,len,halflen,flag=1;
    char str[50];
    clrscr();
    printf("Enter a string:
");
    gets(str);
    len=strlen(str);
    halflen=len/2;
    for(i=0;i<halflen;i++)
    {
        if(str[i]!=str[i+halflen])
            flag=0;
        break;

    }
    if(flag)
        printf("It is a Palindrome.");
    else
        printf("It is not a Palindrome.");
    getch();
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your central comparison is flawed:

if (str[i] != str[i+halflen]) 

This isn't comparing the two characters you think it is.

Try entering "HelloHello" into your program, it will say it is a palindrome!

You need to compare these two:

if (str[i] != str[len-i-1])

(and fix the braces, as suggested in the other answer)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...