Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slice string into letters

Tags:

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".

like image 827
angry_gopher Avatar asked Sep 01 '13 08:09

angry_gopher


People also ask

How do you convert a string to a letter?

To convert a string to list of characters in Python, use the list() method to typecast the string into a list. The list() constructor builds a list directly from an iterable, and since the string is iterable, you can construct a list from it.

How do I split a string into a list in Word?

To convert a string in a list of words, you just need to split it on whitespace. You can use split() from the string class. The default delimiter for this method is whitespace, i.e., when called on a string, it'll split that string at whitespace characters.

How do you split words into letters in Python?

Use the list() class to split a word into a list of letters, e.g. my_list = list(my_str) . The list() class will convert the string into a list of letters.


2 Answers

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

like image 63
zzzz Avatar answered Oct 06 '22 05:10

zzzz


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

like image 33
topskip Avatar answered Oct 06 '22 03:10

topskip