在 Go 中,如果我有一个字符串变量 s:
var s string = "a,b,c,d,e"
如何将其转换或拆分或分解为切片或字符串数组,使其变为:
arr[0] = "a"
...
arr[4] = "e"
如果要忽略空元素,可以使用 strings#FieldsFunc:
package main
import (
"fmt"
"strings"
)
func main() {
s := ",a,,b,c,d,e,"
arr := strings.FieldsFunc(s, func(r rune) bool {
return r == ','
})
fmt.Printf("%q\n", arr) // ["a" "b" "c" "d" "e"]
}
package main
import (
"bufio"
"strings"
)
func comma(data []byte, eof bool) (int, []byte, error) {
if eof { return 0, nil, nil }
a := -1
for b, c := range data {
if c == ',' {
if a >= 0 {
return b+1, data[a:b], nil
}
} else if a < 0 {
a = b
}
}
return len(data), data, nil
}
func main() {
s := ",a,,b,c,d,e"
arr := bufio.NewScanner(strings.NewReader(s))
arr.Split(comma)
for arr.Scan() {
println(arr.Text())
}
}