How to cut off last rune in UTF string? This method is obviously incorrect:
package main
import ("fmt"
"unicode/utf8")
func main() {
string := "你好"
length := utf8.RuneCountInString(string)
// how to cut off last rune in UTF string?
// this method is obviously incorrect:
withoutLastRune := string[0:length-1]
fmt.Println(withoutLastRune)
}
Almost,
utf8 package has a function to decode the last rune in a string which also returns its length. Cut that number of bytes off the end and you are golden:
str := "你好"
_, lastSize := utf8.DecodeLastRuneInString(str)
withoutLastRune := str[:len(str)-lastSize]
fmt.Println(withoutLastRune)
Using DecodeLastRuneInString is the best answer. I'll just note that if you prize simpler code over run time efficiency, you can do
s := []rune(str) fmt.Println(string(s[:len(s)-1]))