1.利用shell脚本来实现对字符串指定位置的反转操作。以下为reverseStr.sh文件。
#!/bin/bash
function showHelp(){
echo -e "Useage: \n ./reverseStr str startIndex endIndex\n"
echo "ex: ./reverseStr.sh helloWorld 2 5"
}
if [ "$1" = "" -o "$2" = "" ];then
showHelp
exit
fi
if [ "$3" = "" ];then
showHelp
exit
fi
tmp_str=$1
len_str=${#tmp_str}
if [ $2 -lt 0 ];then
startIndex=0
else
startIndex=$2
fi
#输入的内容大于字符串的长度时,以当前字符串的长度为反转的最后字符
if [ $3 -gt $len_str ];then
endIndex=$len_str
else
endIndex=$3
fi
#echo "str=$tmp_str startIndex=$startIndex endIndex=$endIndex"
if [ $startIndex -eq 0 ];then
before_str=""
else
before_str="${tmp_str:0:$startIndex}"
fi
if [ $endIndex -eq $len_str ];then
end_str=""
else
end_str="${tmp_str:$endIndex:$len_str}"
fi
lastIndex=`expr $endIndex - $startIndex`
str=${tmp_str:$startIndex:$lastIndex}
len=${#str}
if [[ $((len % 2)) -ne 0 ]];then
for (( i=0,j=$len; i < j; i++,j-- ))
do
tmp_start=${str:$i:1}
tmp_end=${str:$j:1}
str_f=$tmp_start$str_f
str_e=$str_e$tmp_end
echo "tmp_start=$tmp_start tmp_end=$tmp_end str_f=$str_f str_e=$str_e"
done
else
len=`expr $len - 1`
for (( i=0,j=$len; i < j; i++,j-- ))
do
tmp_start=${str:$i:1}
tmp_end=${str:$j:1}
str_f=$tmp_start$str_f
str_e=$str_e$tmp_end
echo "tmp_start=$tmp_start tmp_end=$tmp_end str_f=$str_f str_e=$str_e"
done
fi
echo "str=$str"
str_final=$str_e$str_f
echo $before_str$str_final$end_str
2.输出结果
[root@localhost json]# bash reverseStr.sh helloworld 3 6
tmp_start=l tmp_end= str_f=l str_e=
tmp_start=o tmp_end=w str_f=ol str_e=w
str=low
helwolorld