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?
You can split a string by each character using an empty string('') as the splitter. In the example below, we split the same message using an empty string. The result of the split will be an array containing all the characters in the message string.
Split() is used to break a string into a list of substrings using a specified delimiter. It returns the substrings in the form of a slice.
Using split() When the string is empty and no separator is specified, split() returns an array containing one empty string, rather than an empty array. If the string and separator are both empty strings, an empty array is returned.
Split(Char, Int32, StringSplitOptions) Splits a string into a maximum number of substrings based on the provided character separator, optionally omitting empty substrings from the result.
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.
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
andsep
are empty, Split returns an empty slice.
https://golang.org/pkg/strings#Split
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With