截取UTF字符串的最后一个符文。

huangapple go评论107阅读模式
英文:

cut off last rune in UTF string

问题

如何截取UTF字符串中的最后一个符文?
这种方法显然是不正确的:

  1. package main
  2. import (
  3. "fmt"
  4. "unicode/utf8"
  5. )
  6. func main() {
  7. string := "你好"
  8. length := utf8.RuneCountInString(string)
  9. // 如何截取UTF字符串中的最后一个符文?
  10. // 这种方法显然是不正确的:
  11. withoutLastRune := string[0:length-1]
  12. fmt.Println(withoutLastRune)
  13. }

Playground

英文:

How to cut off last rune in UTF string?
This method is obviously incorrect:

  1. package main
  2. import ("fmt"
  3. "unicode/utf8")
  4. func main() {
  5. string := "你好"
  6. length := utf8.RuneCountInString(string)
  7. // how to cut off last rune in UTF string?
  8. // this method is obviously incorrect:
  9. withoutLastRune := string[0:length-1]
  10. fmt.Println(withoutLastRune)
  11. }

Playground

答案1

得分: 4

几乎完成了,

utf8包中有一个函数可以解码字符串中的最后一个符文,并返回其长度。只需将该长度的字节数从字符串末尾截取掉即可:

  1. str := "你好"
  2. _, lastSize := utf8.DecodeLastRuneInString(str)
  3. withoutLastRune := str[:len(str)-lastSize]
  4. fmt.Println(withoutLastRune)

playground

英文:

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:

  1. str := "你好"
  2. _, lastSize := utf8.DecodeLastRuneInString(str)
  3. withoutLastRune := str[:len(str)-lastSize]
  4. fmt.Println(withoutLastRune)

playground

答案2

得分: 0

使用DecodeLastRuneInString是最好的答案。我只想指出,如果你更看重简洁的代码而不是运行时效率,你可以这样做:

  1. s := []rune(str)
  2. 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>

huangapple
  • 本文由 发表于 2015年6月2日 10:42:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/30586467.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定