英文:
How to slice a string using a delimiter
问题
var s string = "a,b,c,d,e"
arr := strings.Split(s, ",")
英文:
In Go, if I have a string variable s:
var s string = "a,b,c,d,e"
How can I convert or split or explode it into a slice or an array of strings so that it will become:
arr[0] = "a"
...
arr[4] = "e"
答案1
得分: 83
你应该使用strings
包来实现。
stringSlice := strings.Split(s, ",")
http://play.golang.org/p/UKZbcuJUPP
英文:
You should use the strings
package for that.
stringSlice := strings.Split(s, ",")
答案2
得分: 2
如果你想忽略空元素,你可以使用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"]
}
或者使用bufio#Scanner.Split:
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())
}
}
英文:
If you want to ignore empty elements, you can use
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())
}
}
答案3
得分: 0
尝试这个:
package main
import "fmt"
func main() {
var s string = "a,b,c,d,e"
var arr []string
start := 0
for i := 0; i < len(s); i++ {
if s[i] == ',' {
arr = append(arr, s[start:i])
start = i + 1
}
}
if start < len(s) {
arr = append(arr, s[start:])
}
fmt.Print(arr)
}
英文:
Try this one:
package main
import "fmt"
func main() {
var s string = "a,b,c,d,e"
var arr []string
start := 0
for i := 0; i < len(s); i++ {
if s[i] == ',' {
arr = append(arr, s[start:i])
start = i + 1
}
}
if start < len(s) {
arr = append(arr, s[start:])
}
fmt.Print(arr)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论