Check if the String is Palindrome (C++ & Java Program)

A palindrome string means the reverse of string is equal to the original string. 

C++ Program


#include <iostream>
#include <algorithm>
#include <string>

bool isPalindrome(const std::string& str)
{
   std::string temp(str);
   std::transform(temp.begin(), temp.end(), temp.begin(), ::tolower);
   return temp == std::string(temp.rbegin(), temp.rend());
}

int main()
{
  std::string word;
  std::cout << "Enter the String \n";
  std::getline(std::cin, word);

  if(isPalindrome(word))
    std::cout << "The string " << word << " is palindrome \n";
  else
    std::cout << "The string " << word << " is not palindrome \n";
  return 0;
}
 
We have written #include <algorithm> beacuse we are using transform function which is in the Standard Template Library: Algorithm. You can know more about Transform from C++ STL : An example of Transform Algorithm.


We have written std::transform(temp.begin(), temp.end(), temp.begin(), ::tolower); because transform function converts all the characters into lowercase. 

Output

Java Program

import java.util.Scanner;

public class Palindrome
{
  public static void main(String args[])
  {
    String word = "";
    String reverse = "";
    Scanner in = new Scanner(System.in);

    System.out.println("Enter the String");

    word = in.nextLine();
    int length = word.length();
    for(int i = length; i > 0; i--)
    {
      reverse += word.charAt(i-1);
    }

    if(word.equalsIgnoreCase(reverse))
    {
      System.out.println("The string "+word+" is palindrome");
    }
    else
    {
      System.out.println("The string "+word+" is not palindrome");
    }
  }
}
 
Here equalsIgnoreCase() checks whether both strings are equal and ignores whether characters are lowercase or uppercase.

Output


You can find these codes on Github from here and you can download and copy.

Other solutions in Java from Geeksforgeeks

Reference: