Slice string into letters

后端 未结 4 1718
予麋鹿
予麋鹿 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:41

    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.

    0 讨论(0)
  • 2021-02-01 19:47

    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 讨论(0)
  • 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).

    0 讨论(0)
  • 2021-02-01 19:56

    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

    0 讨论(0)
提交回复
热议问题