import (
"bytes"
)
//支持中文截取, 支持end 负数截取
func SubStr(source interface{}, start int, end int) string {
str := source.(string)
var r = []rune(str)
length := len(r)
subLen := end - start
for {
if start < 0 {
break
}
if start == 0 && subLen == length {
break
}
if end > length {
subLen = length - start
}
if end < 0 {
subLen = length - start + end
}
var substring bytes.Buffer
if end > 0 {
subLen = subLen + 1
}
for i := start; i < subLen; i++ {
substring.WriteString(string(r[i]))
}
str = substring.String()
break
}
return str
}
调用
func main() {
a := tools.SubStr("a我a爱b你中国,打的-1", 1,-1)
fmt.Println(a)
}
输出
我a爱b你中国,打的
有疑问加站长微信联系(非本文作者)