write a method to check whether a string is a palindrome or not code example

Example 1: Java program to check whether string is palindrome using library methods

public class StringPalindromeJava
{
   public static void isPalindrome(String str)
   {
      String strReverse = new StringBuffer(str).reverse().toString();
       // checking for palindrome
      if(str.equals(strReverse))
      {
         System.out.println(str + " is palindrome string.");
      }
      else
      {
         System.out.println(str + " is not palindrome string.");
      }
   }
   public static void main(String[] args)
   {
      // palindrome java
      isPalindrome("eye");
      isPalindrome("rotator");
   }
}

Example 2: Write a function that tests whether a string is a palindrome

def palindrome_check(string):
    string = list(string)
    tmp = []
    #remove any spaces
    for x in range(0, len(string)):
        if(string[x] != " "):
            tmp.append(string[x].lower())
    
            
    #now reverse the string
    array1 = []
    i = 0
    j = len(tmp)-1

    while(i < len(tmp)):
        array1.append(tmp[j])
        i += 1
        j -= 1

    #check if array1 is equal to the string
    counter = 0
    for x in range(0, len(tmp)):
        if(tmp[x] == array1[x]):
            counter += 1

    #if the counter is equal to the length of the string then the word
    #is the same
    if(counter == len(tmp)):
        return True
    
    return False

Tags:

Java Example