在Go中,如果我有一个字符串变量s:
var s string = "a,b,c,d,e"
如何将其转换或拆分或分解为切片或字符串数组,以便它变为:
arr[0] = "a"
...
arr[4] = "e"
答案 0 :(得分:44)
答案 1 :(得分:1)
如果你想忽略空元素,你可以使用 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())
}
}