Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to string split an empty string in Go

Tags:

arrays

string

go

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?

like image 877
Peter Bengtsson Avatar asked Feb 04 '15 20:02

Peter Bengtsson


People also ask

Can you split an empty string?

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.

How do you split a string in go?

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.

What happens when split empty string?

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.

How do you split a string into characters?

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.


2 Answers

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.

like image 128
zmb Avatar answered Sep 21 '22 15:09

zmb


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

like image 42
Zombo Avatar answered Sep 24 '22 15:09

Zombo