How to index characters in a Golang string?

前端 未结 9 1806
小鲜肉
小鲜肉 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 09:55

    Another Solution to isolate a character in a string

    package main
    import "fmt"
    
       func main() {
            var word string = "ZbjTS"
    
           // P R I N T 
           fmt.Println(word)
           yo := string([]rune(word)[0])
           fmt.Println(yo)
    
           //I N D E X 
           x :=0
           for x < len(word){
               yo := string([]rune(word)[x])
               fmt.Println(yo)
               x+=1
           }
    
    }
    

    for string arrays also:

    fmt.Println(string([]rune(sArray[0])[0]))
    

    // = commented line

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

    Can be done via slicing too

    package main
    
    import "fmt"
    
    func main() {
        fmt.Print("HELLO"[1:2])
    }
    

    NOTE: This solution only works for ASCII characters.

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

    You can also try typecasting it with string.

    package main
    
    import "fmt"
    
    func main() {
        fmt.Println(string("Hello"[1]))
    }
    
    0 讨论(0)
  • 2020-12-04 10:10

    How about this?

    fmt.Printf("%c","HELLO"[1])
    

    As Peter points out, to allow for more than just ASCII:

    fmt.Printf("%c", []rune("HELLO")[1])
    
    0 讨论(0)
  • 2020-12-04 10:10

    The general solution to interpreting a char as a string is string("HELLO"[1]).

    Rich's solution also works, of course.

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

    String characters are runes, so to print them, you have to turn them back into String.

    fmt.Print(string("HELLO"[1]))

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