2014-01-07 349 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}"