Shell实现字符串指定范围内反转

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值