.

Labels

.

Check for Palindrome

Script to check whether given string is a Palindrome.

palindrome is a word, phrase, number, or other sequence of units that may be read the same way in either direction, with general allowances for adjustments topunctuation and word dividers.
                                             -Wikipediahttp://en.wikipedia.org/wiki/Palindrome )


-------------------------------------------------------------------------------------------------------------------------------------------------
HOW THIS SCRIPT WORKS:
The script divides the string to be checked into two parts of equal number of characters i.e it will divide anna into an and na.
'rev' is command line tool which will reverse the string provided.The second part of the string is reversed and then compared with the first part.
-------------------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------
#!/bin/bash

#to check whether the given string is palindrome.String can contain white spaces

#finding the lenght of the given string
length=$(echo $* | wc -c)


#cutting string into two with one in reversed order
if [[ $((length%2)) == 0 ]];then
   length=$((length/2))   
   l=$(echo $* | cut -c 1-$length)
   r=$(echo $* | rev | cut -c 1-$length)
else
   length=$(((length-1)/2))
   l=$(echo $* | cut -c 1-$length)
   r=$(echo $* | rev | cut -c 1-$length)
fi

#checking both cut parts of the string
if [[ "$l" == "$r" ]];then
   echo "Yes.It is a palindrome"
else
   echo "Sorry.It is not a palindrome"
fi


-------------------------------------------------------------------------------------------


In my computer this script is named palindrome . If I need to check palindrome of a string say malayalam, I will type palindrome malayalam in terminal and press Enter ..





..DONE SIR !!!

Enjoy Linux!!

Dont know what to do with these codes ?? click here


1 comment: