如何截断UTF字符串中的最后一个 rune ? 这种方法显然是错误的:
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)
}
最佳答案
差不多
utf8 包有一个函数可以解码字符串中的最后一个 rune ,该函数还返回其长度。从末尾剪掉这个字节数,你就成功了:
str := "你好"
_, lastSize := utf8.DecodeLastRuneInString(str)
withoutLastRune := str[:len(str)-lastSize]
fmt.Println(withoutLastRune)
关于utf-8 - 截断 UTF 字符串中的最后一个 rune ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30586467/