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

前端 未结 9 552
悲哀的现实
悲哀的现实 2020-11-30 15:36

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  
#include          


        
相关标签:
9条回答
  • 2020-11-30 16:05

    Here's a shorter solution (C++; identical line count for C):

    bool is_p(char const * const str, ptrdiff_t n)
    {
      if (n < 1) return false;
    
      auto p = str, q = str + n - 1;
      while (*(p++) == *(q--))
        if (p >= q)
          return true;
      return false;
    }
    
    0 讨论(0)
  • 2020-11-30 16:06

    You can also use STL to check if a given string is palindrome using function equal. Lets say you have an std::string named x, then the following function call determines if x is palindrome

    equal(x.begin(), x.begin() + x.size() / 2, x.rbegin());
    
    0 讨论(0)
  • 2020-11-30 16:10

    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)

    0 讨论(0)
提交回复
热议问题