dtyqflrr775518
dtyqflrr775518
2019-07-12 09:33
采纳率: 100%
浏览 2.5k
已采纳

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

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

varString := "Bob,Mark,"

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

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

4条回答 默认 最新

  • doubingqi5829
    doubingqi5829 2019-07-12 11:03
    已采纳

    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
    
    点赞 评论
  • douyin8813
    douyin8813 2019-07-12 09:36

    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.

    点赞 评论
  • drlh197610
    drlh197610 2019-07-12 13:33

    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

    点赞 评论
  • dragonsun00000
    dragonsun00000 2019-07-12 22:54
    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.

    点赞 评论

相关推荐