capypad
0 day streak
go / beginner
Snippet

String Indexing and Slicing

Go strings are byte arrays, not rune arrays. `len(s)` returns byte count, which differs for Unicode. Use `len([]rune(s))` for actual character count. Slice bytes directly with `s[:5]` but use runes for character-level operations.

snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package main
 
import (
"fmt"
"strings"
)
 
func main() {
s := "Hello, 世界"
fmt.Printf("Length in bytes: %d\n", len(s))
fmt.Printf("Length in runes: %d\n", len([]rune(s)))
fmt.Println("First 5 bytes:", s[:5])
fmt.Println("First rune:", string([]rune(s)[:1]))
fmt.Println("Contains 'World':", strings.Contains(s, "World"))
fmt.Println("Contains '世界':", strings.Contains(s, "世界"))
fmt.Println("HasPrefix 'Hello':", strings.HasPrefix(s, "Hello"))
fmt.Println("Join:", strings.Join([]string{"a","b"}, "-"))
}
Breakdown
1
len(s)
Returns 13 bytes (H,e,l,l,o,',',space = 7 ASCII + 3 bytes per Chinese char * 2)
2
len([]rune(s))
Returns 8 runes (actual characters)
3
s[:5]
Slices first 5 bytes, works for ASCII
4
strings.Contains(s, "世界")
Works with Unicode strings correctly