dtyqflrr775518
dtyqflrr775518
采纳率100%
2019-07-12 09:33

如何在golang中删除字符串中的最后一个字母?

  • IT行业问题
  • 计算机技术
  • it技术
  • 编程语言问答
  • 互联网问答
已采纳

假设我有一个字符串名为 varString。

varString := "Bob,Mark,"

问: 如何从字符串中删除最后一个字母? 在上面的例子中就是指第二个逗号。

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

4条回答

  • doubingqi5829 doubingqi5829 2年前

    How to remove the last letter from the string?


    In Go, character strings are UTF-8 encoded. Unicode UTF-8 is a variable-length character encoding which uses one to four bytes per Unicode character (code point).

    For example,

    package main
    
    import (
        "fmt"
        "unicode/utf8"
    )
    
    func trimLastChar(s string) string {
        r, size := utf8.DecodeLastRuneInString(s)
        if r == utf8.RuneError && (size == 0 || size == 1) {
            size = 0
        }
        return s[:len(s)-size]
    }
    
    func main() {
        s := "Bob,Mark,"
        fmt.Println(s)
        s = trimLastChar(s)
        fmt.Println(s)
    }
    

    Playground: https://play.golang.org/p/qyVYrjmBoVc

    Output:

    Bob,Mark,
    Bob,Mark
    
    点赞 评论 复制链接分享
  • dragonsun00000 dragonsun00000 2年前
    newStr := strings.TrimRightFunc(str, func(r rune) bool {
        return !unicode.IsLetter(r) // or any other validation can go here
    })
    

    This will trim anything that isn't a letter on the right hand side.

    点赞 评论 复制链接分享
  • drlh197610 drlh197610 2年前

    Here's a much simpler method that works for unicode strings too:

    func removeLastRune(s string) string {
        r := []rune(s)
        return string(r[:len(r)-1])
    }
    

    Playground link: https://play.golang.org/p/ezsGUEz0F-D

    点赞 评论 复制链接分享
  • douyin8813 douyin8813 2年前

    Something like this:

    s := "Bob,Mark,"
    s = s[:len(s)-1]
    

    Note that this does not work if the last character is not represented by just one byte.

    点赞 评论 复制链接分享

为你推荐