HiveBrain v1.2.0
Get Started
← Back to all entries
snippetgoCritical

How to index characters in a Golang string?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
indexhowgolangcharactersstring

Problem

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

package main

import "fmt"

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


Does Golang have function to convert a char to byte and vice versa?

Solution

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

Code Snippets

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
}

Context

Stack Overflow Q#15018545, score: 252

Revisions (0)

No revisions yet.