有些场景需要获取字符串按某个字符切割之后,获取最后,有个比较好的实践分享
strings.LastIndex 如果没有匹配到,则返回-1
package main
import (
"fmt"
"strings"
)
func main() {
ss := []string{"", ":", "a:", "a:b", "a:b:c", "abc"}
/*
'' => ''
':' => ''
'a:' => ''
'a:b' => 'b'
'a:b:c' => 'c'
'abc' => 'abc'
*/
for _, s := range ss {
fmt.Printf("'%s' => '%s'\n", s, s[strings.LastIndex(s, ":")+1:])
}
}
参考链接: