如何在Go中拆分空字符串

huangapple go评论71阅读模式
英文:

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))
}

Playground链接

这是有道理的。如果你想用逗号字符作为分隔符来分割字符串"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))
}

Playground link

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
}

这在文档中有说明:

如果ssep都为空,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.

https://golang.org/pkg/strings#Split

答案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)
}

huangapple
  • 本文由 发表于 2015年2月5日 04:33:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/28330908.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定