Truncate Strings On Rune Boundaries
Cut a string to a rune limit without splitting multibyte characters: range walks rune boundaries so slicing always lands between characters.
Code
package main
import (
"fmt"
"unicode/utf8"
)
// 按最大 rune 数截断:绝不切断多字节字符中间
func truncate(s string, max int) string {
if utf8.RuneCountInString(s) <= max {
return s
}
count := 0
for index := range s { // range 按 rune 起始字节偏移迭代
if count == max {
return s[:index]
}
count++
}
return s
}
func main() {
long := "héllo 世界 🌍✨"
fmt.Println(truncate(long, 5))
fmt.Println(truncate(long, 11))
fmt.Println(truncate(long, 99))
}The loop that lands between characters
truncate(s, max) first short-circuits with utf8.RuneCountInString(s) <= max, returning the input untouched. Otherwise it walks for index := range s — Go’s range over a string yields the byte offset where each rune starts — counting runes in count and returning s[:index] exactly when count == max. Because index is always a rune-start offset, the slice never lands inside a multi-byte character.
The three cuts
héllo
héllo 世界 🌍✨
héllo 世界 🌍✨
The demo string "héllo 世界 🌍✨" is 11 runes (accents, CJK, and emoji each count as one). Truncating to 5 stops at the offset after héllo; the limits 11 and 99 both exceed the rune count, so the guard returns the full string — no error, no padding, just the whole input.
The line that cuts safely
if count == max {
return s[:index]
}
A naive s[:max] would slice by bytes and could split a UTF-8 sequence mid-character, producing invalid output — measuring in runes and cutting at the recorded byte offset is what keeps the result well-formed.
Interactive Tools for This Topic
FAQ
- How do you run Truncate Strings On Rune Boundaries?
- Run it as a complete program — compile or interpret the file directly; there is nothing to install first.
Report a problem with this exampleOpens a pre-filled issue on GitHub.