Golang实现字符串长度截取,支持正反向

​func main(){fmt.Println( SubStr("helloword", -1, 1) )}// start:起始下标,负数从尾部开始,-1
​
func main(){fmt.Println( SubStr("helloword", -1, 1) )}// start:起始下标,负数从尾部开始,-1为最后一个
// length:截取长度,负数表示截取到末尾
func SubStr(str string, start int, length int) (result string) {s := []rune(str)total := len(s)if total == 0 {return}// 允许从尾部开始计算if start < 0 {start = total + startif start < 0 {return}}if start > total {return}// 到末尾if length < 0 {length = total}end := start + lengthif end > total {result = string(s[start:])} else {result = string(s[start:end])}return
}​