英文:
cut off last rune in UTF string
问题
如何截取UTF字符串中的最后一个符文?
这种方法显然是不正确的:
package main
import (
"fmt"
"unicode/utf8"
)
func main() {
string := "你好"
length := utf8.RuneCountInString(string)
// 如何截取UTF字符串中的最后一个符文?
// 这种方法显然是不正确的:
withoutLastRune := string[0:length-1]
fmt.Println(withoutLastRune)
}
英文:
How to cut off last rune in UTF string?
This method is obviously incorrect:
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)
}
答案1
得分: 4
几乎完成了,
utf8包中有一个函数可以解码字符串中的最后一个符文,并返回其长度。只需将该长度的字节数从字符串末尾截取掉即可:
str := "你好"
_, lastSize := utf8.DecodeLastRuneInString(str)
withoutLastRune := str[:len(str)-lastSize]
fmt.Println(withoutLastRune)
英文:
Almost,
utf8 package has a function to decode the last rune in a string which also returns its length. Cut that number of bytes off the end and you are golden:
str := "你好"
_, lastSize := utf8.DecodeLastRuneInString(str)
withoutLastRune := str[:len(str)-lastSize]
fmt.Println(withoutLastRune)
答案2
得分: 0
使用DecodeLastRuneInString是最好的答案。我只想指出,如果你更看重简洁的代码而不是运行时效率,你可以这样做:
s := []rune(str)
fmt.Println(string(s[:len(s)-1]))
英文:
Using DecodeLastRuneInString is the best answer. I'll just note that if you prize simpler code over run time efficiency, you can do
<pre>
s := []rune(str)
fmt.Println(string(s[:len(s)-1]))
</pre>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论