在Golang中按指定分隔符拆分字符串
strings
strings.Split
func Split(s, sep string) []string
ssepssep
Split
package main
import (
"fmt"
"strings"
)
func main() {
str := "hello,world"
arr := strings.Split(str, ",")
fmt.Println(arr)
}
输出结果为:
[hello world]
分割符为多个字符的字符串
strings.SplitNstrings.FieldsFuncstrings.SplitNstrings.FieldsFunc
strings.SplitN
package main
import (
"fmt"
"strings"
)
func main() {
str := "hello-world,xiaoming,good"
arr := strings.SplitN(str, "-", 2)
fmt.Println(arr)
}
输出结果为:
[hello world,xiaoming,good]
自定义分割符
strings.FieldsFuncrune
下面是一个使用自定义函数进行字符串分割的示例代码: