Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
390 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 Reply

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...