How to slice one string in Go language into array of string letters it contains?
For example, turn string \"abc\" into array \"a\", \"b\", \"c\".
I think Split is what you're looking for:
func Split(s, sep string) []string
If sep
is an empty string
, it will split the string into single characters:
Split slices s into all substrings separated by sep and returns a slice of the substrings between those separators. If sep is empty, Split splits after each UTF-8 sequence. It is equivalent to SplitN with a count of -1.
The easiest way is to split.
var userString = "some string to split"
newArr:= strings.Split(userString, "") // split on each char
fmt.Println(newArr[2]) // will print "m"
Use a conversion to runes, for example
package main
import "fmt"
func main() {
s := "Hello, 世界"
for i, r := range s {
fmt.Printf("i%d r %c\n", i, r)
}
fmt.Println("----")
a := []rune(s)
for i, r := range a {
fmt.Printf("i%d r %c\n", i, r)
}
}
Playground
Output:
i0 r H
i1 r e
i2 r l
i3 r l
i4 r o
i5 r ,
i6 r
i7 r 世
i10 r 界
----
i0 r H
i1 r e
i2 r l
i3 r l
i4 r o
i5 r ,
i6 r
i7 r 世
i8 r 界
From the link:
Converting a value of a string type to a slice of runes type yields a slice containing the individual Unicode code points of the string. If the string is empty, the result is []rune(nil).
Use strings.Split on it:
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Printf("%#v\n",strings.Split("abc", ""))
}
http://play.golang.org/p/1tNfu0iyHS