假设我有一个字符串名为 varString。
varString := "Bob,Mark,"
问: 如何从字符串中删除最后一个字母? 在上面的例子中就是指第二个逗号。
假设我有一个字符串名为 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