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

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

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)
}

Playground

英文:

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)
}

Playground

答案1

得分: 4

几乎完成了,

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

str := "你好"
_, lastSize := utf8.DecodeLastRuneInString(str)
withoutLastRune := str[:len(str)-lastSize]
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:

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

playground

答案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>

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:

确定