英文:
How to string split an empty string in Go
问题
在Python中,如果我执行以下操作:
parts = "".split(",")
print(parts, len(parts))
输出结果为:
[], 0
如果我在Go中执行相同的操作:
parts := strings.Split("", ",")
fmt.Println(parts, len(parts))
输出结果为:
[], 1
为什么长度为1,即使其中没有任何内容?
英文:
In Python if I do...:
parts = "".split(",")
print parts, len(parts)
The output is:
[], 0
If I do the equivalent in Go...:
parts = strings.Split("", ",")
fmt.Println(parts, len(parts))
the output is:
[], 1
How can it have a length of 1 if there's nothing in it?
答案1
得分: 14
strings.Split
的结果是一个只有一个元素的切片 - 空字符串。
fmt.Println
只是没有显示它。尝试这个例子(注意最后一个打印的变化)。
package main
import "fmt"
import "strings"
func main() {
groups := strings.Split("one,two", ",")
fmt.Println(groups, len(groups))
groups = strings.Split("one", ",")
fmt.Println(groups, len(groups))
groups = strings.Split("", ",")
fmt.Printf("%q, %d\n", groups, len(groups))
}
这是有道理的。如果你想用逗号字符作为分隔符来分割字符串"HelloWorld"
,你期望的结果应该是"HelloWorld"
,与你的输入相同。
英文:
The result of strings.Split
is a slice with one element - the empty string.
fmt.Println
is just not displaying it. Try this example (notice the change to the last print).
package main
import "fmt"
import "strings"
func main() {
groups := strings.Split("one,two", ",")
fmt.Println(groups, len(groups))
groups = strings.Split("one", ",")
fmt.Println(groups, len(groups))
groups = strings.Split("", ",")
fmt.Printf("%q, %d\n", groups, len(groups))
}
This makes sense. If you wanted to split the string "HelloWorld"
using a ,
character as the delimiter, you'd expect the result to be "HelloWorld"
- the same as your input.
答案2
得分: 3
只有当两个字符串都为空时,才能得到这个结果:
package main
import (
"fmt"
"strings"
)
func main() {
parts := strings.Split("", "")
fmt.Println(parts, len(parts)) // [] 0
}
这在文档中有说明:
如果
s
和sep
都为空,Split返回一个空切片。
https://golang.org/pkg/strings#Split
英文:
You can only get that result if both strings are empty:
package main
import (
"fmt"
"strings"
)
func main() {
parts := strings.Split("", "")
fmt.Println(parts, len(parts)) // [] 0
}
Which is documented:
> If both s
and sep
are empty, Split returns an empty slice.
答案3
得分: 3
如果你习惯了Python中str.split的行为,你会发现对strings.Split进行一个小包装很有帮助。
func realySplit(s, sep string) []string {
if len(s) == 0 {
return []string{}
}
return strings.Split(s, sep)
}
英文:
If you're used to Python's behaviour in str.split, you'll find a tiny wrapper around strings.Split helpful.
func realySplit(s, sep string) []string {
if len(s) == 0 {
return []string{}
}
return strings.Split(s, sep)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论