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).
${#a}
.flag
implicitly - if you pass the midpoint, the string is a palindrome.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.