Go语言的strings包中提供了字符串切割的函数,其中Split和SplitN都是切割字符串的函数。
strings.SplitN函数的用法:
func SplitN(s, sep string, n int) []string
函数说明:
- s:原始字符串
- sep:分隔字符串
- n:分隔次数,为0时表示分隔所有;大于0时表示分隔n-1次
函数返回值:
- []string:分隔后的字符串数组
示例代码:
str := "hello world,hello Go,hello PHP,hello Python"
s1 := strings.SplitN(str, ",", 2)
fmt.Println(s1) // [hello world hello Go,hello PHP,hello Python]
s2 := strings.SplitN(str, ",", 0)
fmt.Println(s2) // [hello world hello Go hello PHP hello Python]
Split函数的用法:
func Split(s, sep string) []string
函数说明:
- s:原始字符串
- sep:分隔字符串
函数返回值:
- []string:分隔后的字符串数组
示例代码:
str := "hello world,hello Go,hello PHP,hello Python"
s1 := strings.Split(str, ",")
fmt.Println(s1) // [hello world hello Go hello PHP hello Python]
可以看出,Split函数等价于SplitN函数中n值为0的情况。区别在于SplitN函数支持限制分隔次数,而Split函数不支持。