Go 字符串分隔

函数 strings.Split

strings.Split(s, sep string) []string

使用参数sep作为分隔字符串分隔参数s,返回一个字符串数组

代码:

import (
    "fmt"
    "strings"
)
func main() {
    fmt.Printf("%q\n", strings.Split("a,b,c", ","))
    fmt.Printf("%q\n", strings.Split("a man a plan a canal panama", "a "))
    fmt.Printf("%q\n", strings.Split(" xyz ", ""))
    fmt.Printf("%q\n", strings.Split("", "Bernardo O'Higgins"))
}

输出:

["a" "b" "c"]
["" "man " "plan " "canal panama"]
[" " "x" "y" "z" " "]
[""]

函数 strings.SplitN

func SplitN(s, sep string, n int) []string

使用参数sep作为分隔字符串分隔参数s,且可以指定参数n设置分隔次数。返回一个字符串数组

代码:

fmt.Printf("%q\n", strings.SplitN("a,b,c", ",", 2))

输出:

["a" "b,c"]