2014-01-07 113 views
1

以下KornShell(ksh)脚本应检查字符串是否为回文。我正在使用ksh88,而不是ksh93ksh中的错误替换错误

#!/bin/ksh 
strtochk="naman" 
ispalindrome="true" 
len=${#strtochk} 
i=0 
j=$((${#strtochk} - 1)) 
halflen=$len/2 
print $halflen 
while ((i < $halflen)) 
do 
if [[ ${strtochk:i:1} == ${strtochk:j:1} ]];then 
     (i++) 
     (j--) 
else 
    ispalindrome="false" 
    break 
fi 
done 

print ispalindrome 

但我在下面这行越来越不好替代误差:if [[ ${strtochk:i:1} == ${strtochk:j:1} ]];then

可有人请让我知道我做错了吗?

回答

1

${strtochk:i:1}${strtochk:j:1}中的子字符串语法在ksh88中不可用。可以升级到ksh93,也可以使用awk或bash等其他语言。

+0

请解释如何用awk。这就是我正在使用ksh 88的全部重点 – Programmer

1

你可以用这个便携式线替换你的测试:

if [ "$(printf "%s" "$strtochk" | cut -c $i)" = 
    "$(printf "%s" "$strtochk" | cut -c $j)" ]; then 

您还需要与

halflen=$((len/2)) 

和ksh93的/ bash的语法来代替可疑

halflen=$len/2 

$((i++)) 
$((j--)) 

这个ksh88之一:

i=$((i+1)) 
j=$((j-1)) 
0

如何检查,如果输入的字符串是回文这KornShell(KSH)脚本。

isPalindrome.ksh

#!/bin/ksh 

#----------- 
#---Main---- 
#----------- 
echo "Starting: ${PWD}/${0} with Input Parameters: {1: ${1} {2: ${2} {3: ${3}" 
echo Enter the string 
read s 
echo $s > temp 
rvs="$(rev temp)" 
if [ $s = $rvs ]; then 
    echo "$s is a palindrome" 
else 
    echo "$s is not a palindrome" 
fi 
echo "Exiting: ${PWD}/${0}"