How to index characters in a Golang string?

前端 未结 9 1807
小鲜肉
小鲜肉 2020-12-04 09:15

How to get an \"E\" output rather than 69?

package main

import \"fmt\"

func main() {
    fmt.Print(\"HELLO\"[1])
}

Does Golang have funct

相关标签:
9条回答
  • 2020-12-04 10:13

    Try this to get the charecters by their index

    package main
    
    import (
          "fmt"
          "strings"
    )
    
    func main() {
       str := strings.Split("HELLO","")
        fmt.Print(str[1])
    }
    
    0 讨论(0)
  • 2020-12-04 10:20

    Go doesn't really have a character type as such. byte is often used for ASCII characters, and rune is used for Unicode characters, but they are both just aliases for integer types (uint8 and int32). So if you want to force them to be printed as characters instead of numbers, you need to use Printf("%c", x). The %c format specification works for any integer type.

    0 讨论(0)
  • 2020-12-04 10:21

    Interpreted string literals are character sequences between double quotes "" using the (possibly multi-byte) UTF-8 encoding of individual characters. In UTF-8, ASCII characters are single-byte corresponding to the first 128 Unicode characters. Strings behave like slices of bytes. A rune is an integer value identifying a Unicode code point. Therefore,

    package main
    
    import "fmt"
    
    func main() {
        fmt.Println(string("Hello"[1]))              // ASCII only
        fmt.Println(string([]rune("Hello, 世界")[1])) // UTF-8
        fmt.Println(string([]rune("Hello, 世界")[8])) // UTF-8
    }
    

    Output:

    e
    e
    界
    

    Read:

    Go Programming Language Specification section on Conversions.

    The Go Blog: Strings, bytes, runes and characters in Go

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