简体   繁体   中英

Palindrome using shell scripting

I have tried to write a code for checking a string if it is a palidrome but dont know where am I going wrong

read a
len=`echo $a|wc -m`
len=`expr $len - 1`
# echo $len
flag=1
for((i=0;i<len/2;i++))
do
    k=`expr $len - $i - 1`
    # echo "${a:$i:1} ${a:$k:1}"
    if((${a:$i:1} != ${a:$k:1}))
    then    
        flag=0 
        break
    fi

done

if(($flag == 1))
then
    echo Palindrome
else
    echo Not Palindrome
fi

Your main problem is that you have used ((..)) instead of [[.. ]] for the string comparison (spacing matters in the latter).

  • You can get length directly with ${#a} .
  • Your algorithm starts from both ends and then increments/decrements towards the middle. So you can get flag implicitly - if you pass the midpoint, the string is a palindrome.
  • You can replace all use of expr with ((.. )) .
  • for ((..)) allows initialising/updating multiple variables.
read a

for (( i=0, k=${#a}-1; i<=k; i++, k-- ))
do
    [[ ${a:$i:1} != ${a:$k:1} ]] && break
done

if (( i>k ))
then
    echo Palindrome
else
    echo Not Palindrome
fi

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM