Cut string to letters

How to chop a single string in Google Go as an array of string letters that it contains?

For example, turn the string "abc" into the array "a", "b", "c".

+8
string go
source share
4 answers

Use conversion for runes, for example

package main import "fmt" func main() { s := "Hello, δΈ–η•Œ" for i, r := range s { fmt.Printf("i%dr %c\n", i, r) } fmt.Println("----") a := []rune(s) for i, r := range a { fmt.Printf("i%dr %c\n", i, r) } } 

Playground


Output:

 i0 r H i1 re i2 rl i3 rl i4 ro i5 r , i6 r i7 r δΈ–i10 r η•Œ---- i0 r H i1 re i2 rl i3 rl i4 ro i5 r , i6 r i7 r δΈ–i8 r η•Œ 

From the link:

Converting a string type value to a rune type piece gives a slice containing individual Unicode string code points. If the line is empty, the result is [] rune (nil).

+13
source share

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

+8
source share

I think Split is what you are looking for:

 func Split(s, sep string) []string 

If sep is an empty string , it will split the string into separate characters:

Split slices s into all substrings separated by sep, and returns a slice of substrings between these separators. If sep is empty, Split is broken after each UTF-8 sequence. This is equivalent to SplitN with the number -1 .

+1
source share

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" 
0
source share

All Articles