Groovy 35- How To Check if a String is a Palindrome

From Wiky:

palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward, such as madam or racecar. Sentence-length palindromes may be written when allowances are made for adjustments to capital letters, punctuation, and word dividers, such as “A man, a plan, a canal, Panama!”, “Was it a car or a cat I saw?” or “No ‘x’ in Nixon”.

Composing literature in palindromes is an example of constrained writing.

The word “palindrome” was coined by the English playwright Ben Jonson in the 17th century from the Greek roots palin (π¿λιν; “again”) and dromos (δρóμος; “way, direction”).

 

Source: https://en.wikipedia.org/wiki/Palindrome

 

So how do we put it in code?

Well lets take an example.

 

Lets say we have the string racecar , how do we write a script to check if this  string is a palindrome.

//First we declare the String variable  
def word = “racecar”  
//now we declare 2 variables, one will hold the string in reverse and 
//one will hold the check done  
def checkDone;  
String reverse=“”;  
//get the size of the word to be checked  
      int length = word.size();  
/ now reverse the word   
      for ( int i = length – 1; i >= 0; i– ){  
         reverse = reverse + word.charAt(i);  
      }  
// and now we check if the original word is equal with the reversed word  
     if(word.equalsIgnoreCase(reverse)){  
        checkDone = “The String  “ +word+ ” is a palindrome” ;     
     }else{  
        checkDone = “The String “ +word+ ” is not a palindrome”;    
     }  
  
println(checkDone )

Leave a Reply

Your email address will not be published. Required fields are marked *