Slice string into letters

后端 未结 4 1732
予麋鹿
予麋鹿 2021-02-01 19:19

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

4条回答
  •  遇见更好的自我
    2021-02-01 19:55

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

提交回复
热议问题