检测字符串str,从toffset处开始,是否以substr为前缀
注意:$3(即toffset)可以忽略,此时检测字符串$1(即str)是否以$2(substr)为前缀1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25# startsWith
function startsWith() {
if [ $# -ne 2 -a $# -ne 3 ]; then
echo "invalid param!"
return
fi
local str="$1"
local substr="$2"
local strLength=${#str}
local substrLength=${#substr}
local toffset=0
if [ $# -eq 3 ]; then
toffset=$3
fi
if [ $toffset -lt 0 -o $toffset -gt $(expr $strLength - $substrLength) ]; then
echo "false"
return
fi
local innerstr="${str:$toffset:$substrLength}"
if [[ "$innerstr" == "$substr" ]]; then
echo "true"
else
echo "false"
fi
}
检测字符串str,是否以substr为后缀
1 | # endsWith |
根据字符下标,截取字符串
可接收2或3个参数,第1个参数($1)为源字符串(str),第2个参数($2)为截取的开始索引(beginIndex),第3个参数($3)为截取的结束索引(endIndex),若忽略第3个参数,则endIndex为源字符串(str)的长度
注意: 截取的子字符串,包含 beginIndex 位置上的字符,不包含 endIndex 位置上的字符1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28# substring
function substring() {
if [ $# -ne 2 -a $# -ne 3 ] ; then
echo "invalid param!"
return
fi
local str="$1"
local strLength=${#str}
local beginIndex=$2
local endIndex=$strLength
if [ $# -eq 3 ]; then
endIndex=$3
fi
if [ $beginIndex -lt 0 ]; then
echo "String index out of range: $beginIndex"
return
fi
if [ $endIndex -gt $strLength ]; then
echo "String index out of range: $endIndex"
return
fi
local substrLength=$(expr $endIndex - $beginIndex)
if [ $substrLength -lt 0 ]; then
echo "String index out of range: $substrLength"
return
fi
echo "${str:$beginIndex:$substrLength}"
}