douzhan3900 2015-06-02 02:42
浏览 115
已采纳

截断UTF字符串中的最后一个符文

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)
}

Playground

  • 写回答

2条回答 默认 最新

  • douliaodun9153 2015-06-02 02:49
    关注

    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)
    

    playground

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置