切断 UTF 字符串中的最后一个符文
cut off last rune in UTF string
如何截掉UTF字符串中的最后一个符文?
这个方法明显不对:
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)
}
差不多,
utf8 包具有解码字符串中最后一个符文的功能,该字符串也是 returns 其长度。把最后的字节数去掉,你就成功了:
str := "你好"
_, lastSize := utf8.DecodeLastRuneInString(str)
withoutLastRune := str[:len(str)-lastSize]
fmt.Println(withoutLastRune)
使用 DecodeLastRuneInString 是最佳答案。我只是注意到,如果您更看重更简单的代码而不是 运行 时间效率,您可以
s := []rune(str)
fmt.Println(string(s[:len(s)-1]))
如何截掉UTF字符串中的最后一个符文? 这个方法明显不对:
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)
}
差不多,
utf8 包具有解码字符串中最后一个符文的功能,该字符串也是 returns 其长度。把最后的字节数去掉,你就成功了:
str := "你好"
_, lastSize := utf8.DecodeLastRuneInString(str)
withoutLastRune := str[:len(str)-lastSize]
fmt.Println(withoutLastRune)
使用 DecodeLastRuneInString 是最佳答案。我只是注意到,如果您更看重更简单的代码而不是 运行 时间效率,您可以
s := []rune(str) fmt.Println(string(s[:len(s)-1]))