检测字符串str,从toffset处开始,是否以substr为前缀

注意:$3(即toffset)可以忽略,此时检测字符串$1(即str)是否以$2(substr)为前缀

# 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为后缀

# endsWith
function endsWith() {
  if [ $# -ne 2 ]; then
    echo "invalid param!"
    return
  fi
  local str="$1"
  local substr="$2"
  local strLength=${#str}
  local substrLength=${#substr}
  echo "$(startsWith "$str" "$substr" $(expr $strLength - $substrLength))"
}

根据字符下标,截取字符串

可接收2或3个参数,第1个参数($1)为源字符串(str),第2个参数($2)为截取的开始索引(beginIndex),第3个参数($3)为截取的结束索引(endIndex),若忽略第3个参数,则endIndex为源字符串(str)的长度
注意: 截取的子字符串,包含 beginIndex 位置上的字符,不包含 endIndex 位置上的字符

# 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}"
}
About Me
后端开发工程师
GitHub Repos