utf-8 - 截断 UTF 字符串中的最后一个 rune

标签 utf-8 go

如何截断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)
}

Playground

最佳答案

差不多

utf8 包有一个函数可以解码字符串中的最后一个 rune ,该函数还返回其长度。从末尾剪掉这个字节数,你就成功了:

str := "你好"
_, lastSize := utf8.DecodeLastRuneInString(str)
withoutLastRune := str[:len(str)-lastSize]
fmt.Println(withoutLastRune)

playground

关于utf-8 - 截断 UTF 字符串中的最后一个 rune ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30586467/

相关文章:

go - 是否可以按输入顺序收集 goroutine 结果?

linux - UTF-8 输入和使用 XGetICValues

mysql - 为什么 mysql 4 不遵守 --character_set_results 和 --default-character-set 命令参数?

unicode - 如何解码带有 unicode 符号的混合字符串?

go - go库中的http服务器是非阻塞的吗?

go - 生成Fyne应用时出现glfw pkg-config错误

html - 谷歌浏览器在移动到另一个页面后不会返回到 UTF-8

mysql - perl 解码西里尔字母字符串

java - Go 和 Java 之间的 IO 性能

linux - fork 的 ptraced 进程挂起