Saturday 24 August 2013

script to check if a string is a palindrome?

A palindrome is a word, phrase, number, or other sequence of symbols or elements, whose meaning may be interpreted the same way in either forward or reverse direction.

Here is a script which will tell you whether a given string is a palindrome or not .

Script:
#!/usr/bin/ksh
len=0
i=1
echo -n "Enter a String: "
read str
len=`echo $str | wc -c`
len=`expr $len - 1`
halfLen=`expr $len / 2`
while [ $i -le $halfLen ]
do
c1=`echo $str|cut -c$i`
c2=`echo $str|cut -c$len`
if [ $c1 != $c2 ] ; then
echo "string is not palindrome"
exit
fi
i=`expr $i + 1`
len=`expr $len - 1`
done
echo "String is Palindrome"

4 comments:

  1. #!/bin/bash
    read name
    echo " "

    name1=`echo $name | rev`
    if [ "$name" == "$name1" ]
    then
    echo "**$name is palindrome**"
    else
    echo "**$name is not a palindrome**"
    fi

    ReplyDelete
  2. damn now that's a efficient script
    but it needed a little correction

    echo "enter the string "
    read name

    name1=$(echo $name | rev) #modified version or alternative to ``
    if [ $name = $name1 ]
    then
    echo "**$name is palindrome**"
    else
    echo "**$name is not a palindrome**"
    fi

    all the credit for this program goes to Pramod Bhat

    ReplyDelete
  3. #!/bin/bash
    echo "Enter a String : "
    read x
    strlen=${#x}
    dec=`expr $strlen - 1`
    counter=0
    divlen=`expr $strlen / 2`
    for ((i=0; i<divlen; i++))
    do
    let1=${x:$i:1}
    let2=${x:$dec:1}
    if [ $let1 = $let2 ]
    then
    counter=`expr $counter + 1`
    dec=`expr $dec - 1`
    fi
    done
    if [ $counter -eq $divlen ]
    then
    echo "It is palindrome"
    else
    echo "It is not palindrome"
    fi

    ReplyDelete
  4. #!/bin/bash
    echo "Enter a String : "
    read x
    strlen=${#x}
    dec=`expr $strlen - 1`
    counter=0
    divlen=`expr $strlen / 2`
    for ((i=0; i<divlen; i++))
    do
    let1=${x:$i:1}
    let2=${x:$dec:1}
    if [ $let1 = $let2 ]
    then
    counter=`expr $counter + 1`
    dec=`expr $dec - 1`
    fi
    done
    if [ $counter -eq $divlen ]
    then
    echo "It is palindrome"
    else
    echo "It is not palindrome"
    fi

    ReplyDelete