Strings, bytes, runes and characters in Go

1 Printing strings

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package main

import "fmt"

func main() {
const sample = "\xbd\xb2\x3d\xbc\x20\xe2\x8c\x98"

fmt.Println("Println:")
fmt.Println(sample)

fmt.Println("Byte loop:")
for i := 0; i < len(sample); i++ {
fmt.Printf("%x ", sample[i])
}
fmt.Printf("\n")

fmt.Println("Printf with %x:")
fmt.Printf("%x\n", sample)

fmt.Println("Printf with % x:")
fmt.Printf("% x\n", sample)

fmt.Println("Printf with %q:")
fmt.Printf("%q\n", sample)

fmt.Println("Printf with %+q:")
fmt.Printf("%+q\n", sample)

fmt.Println("Byte loop with %q:")
for i := 0; i < len(sample); i++ {
fmt.Printf("%q ", sample[i])
}
fmt.Printf("\n")
}

2 UTF-8 and string literals

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package main

import "fmt"

func main() {
const placeOfInterest = `⌘`

fmt.Printf("plain string: ")
fmt.Printf("%s", placeOfInterest)
fmt.Printf("\n")

fmt.Printf("quoted string: ")
fmt.Printf("%+q", placeOfInterest)
fmt.Printf("\n")

fmt.Printf("hex bytes: ")
for i := 0; i < len(placeOfInterest); i++ {
fmt.Printf("%x ", placeOfInterest[i])
}
fmt.Printf("\n")
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package main

import "fmt"

func main() {
const nihongo = "日本語"
for index, runeValue := range nihongo {
fmt.Printf("%#U starts at byte position %d\n", runeValue, index)
}

const str = "abc"
for index, runeValue := range str {
fmt.Printf("%#U starts at byte position %d\n", runeValue, index)
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package main

import (
"fmt"
"unicode/utf8"
)

func main() {
const nihongo = "日本語"
for i, w := 0, 0; i < len(nihongo); i += w {
runeValue, width := utf8.DecodeRuneInString(nihongo[i:])
fmt.Printf("%#U starts at byte position %d\n", runeValue, i)
w = width
}
}
Last Updated 2018-04-08 Sun 18:24.
Render by hexo-renderer-org with Emacs 25.3.2 (Org mode 8.2.10)