Skip to content

Instantly share code, notes, and snippets.

@glxxyz
Last active June 5, 2020 14:08
Show Gist options
  • Save glxxyz/712673d4e3951120a1484a4c2c6aa68d to your computer and use it in GitHub Desktop.
Save glxxyz/712673d4e3951120a1484a4c2c6aa68d to your computer and use it in GitHub Desktop.
Go strings as bytes and runes: 3 for loops and 2 slices
package main
import (
"fmt"
)
// Try it out here: https://repl.it/@glxxyz/RoundedNormalFunction
// It's important to note the different values that 'index' takes
// when using []rune and range
func main() {
s := "HSK东西"
for i:=0; i<len(s); i++ {
fmt.Printf("[]byte: index %v int %v char %c\n", i, s[i], s[i])
}
fmt.Println("")
runes := []rune(s)
for i:=0; i<len(runes); i++ {
fmt.Printf("[]rune: index %v int %v char %c\n", i, runes[i], runes[i])
}
fmt.Println("")
for i, x := range s {
fmt.Printf("range: index %v int %v char %c\n", i, x, x)
}
fmt.Println("")
var fromByteWithoutFirstLast string = s[1:len(s)-1]
fmt.Printf("from byte array without first and last: %v\n", fromByteWithoutFirstLast)
var fromRuneWithoutFirstLast string = string(runes[1:len(runes)-1])
fmt.Printf("from rune array without first and last: %v\n", fromRuneWithoutFirstLast)
}
/*
Output:
[]byte: index 0 int 72 char H
[]byte: index 1 int 83 char S
[]byte: index 2 int 75 char K
[]byte: index 3 int 228 char ä
[]byte: index 4 int 184 char ¸
[]byte: index 5 int 156 char
[]byte: index 6 int 232 char è
[]byte: index 7 int 165 char ¥
[]byte: index 8 int 191 char ¿
[]rune: index 0 int 72 char H
[]rune: index 1 int 83 char S
[]rune: index 2 int 75 char K
[]rune: index 3 int 19996 char 东
[]rune: index 4 int 35199 char 西
range: index 0 int 72 char H
range: index 1 int 83 char S
range: index 2 int 75 char K
range: index 3 int 19996 char 东
range: index 6 int 35199 char 西
from byte array without first and last: SK东�
from rune array without first and last: SK东
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment