Overview
Shorten titles for cards and notifications in Go without cutting a letter in half: count runes instead of bytes, and slice a []rune, not the string.
- a string is UTF-8 bytes, len counts bytes
- []rune(s) gives one item per code point
- s[:n] can split a letter
Short Course
A Go string is UTF-8 bytes, and len counts bytes: len("é") is 2.
[]rune(s) gives one item per rune (a Unicode code point), which for most text is one letter. Trap: s[:n] cuts after n bytes and
can split a letter in half.
s := "café"
len(s) // 5 bytes
len([]rune(s)) // 4 letters
string([]rune(s)[:3]) // "caf"
Task
Write Truncate(title string, limit int) string: if title has more than
limit letters, keep the first limit and add "…"; otherwise return it
unchanged. Example: Truncate("Café crème", 4) → "Café…".
Test Suites
Pending
Next
Output