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

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

varString := "Bob,Mark,"

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

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

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.

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

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.