有些場景需要獲取字符串按某個字符切割之后,獲取最后,有個比較好的實踐分享
strings.LastIndex 如果沒有匹配到,則返回-1
package mainimport ("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:])}
}
參考鏈接:
- go - 返回 Golang 中 strings.Split() slice 的最后一項
- Return last item of strings.Split() slice in Golang