Skip to content

Instantly share code, notes, and snippets.

@jcamilom
Last active May 3, 2018 20:13
Show Gist options
  • Save jcamilom/ffc4ce0c776daad552d3011767885dde to your computer and use it in GitHub Desktop.
Save jcamilom/ffc4ce0c776daad552d3011767885dde to your computer and use it in GitHub Desktop.
[Accessing bytes and runes of a string] Getting the corresponding bytes and runes that compose a string. From https://golangbot.com/strings/ #go #golang #strings
package main
import (
"fmt"
)
func printBytes(s string) {
for i:= 0; i < len(s); i++ {
fmt.Printf("%x ", s[i])
}
}
func printChars(s string) {
runes := []rune(s)
for i:= 0; i < len(runes); i++ {
fmt.Printf("%c ",runes[i])
}
}
func printCharsAndBytes(s string) {
for index, rune := range s {
fmt.Printf("%c starts at byte %d\n", rune, index)
}
}
func main() {
name := "Hello World"
printBytes(name)
fmt.Printf("\n")
printChars(name)
fmt.Printf("\n\n")
name = "Señor"
printBytes(name)
fmt.Printf("\n")
printChars(name)
fmt.Printf("\n")
printCharsAndBytes(name)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment