如何获取 Golang 字符串的最后 X 个字符?

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

How to get the last X Characters of a Golang String?

问题

如果我有字符串"12121211122",并且我想要获取最后3个字符(例如"122"),在Go语言中是否有可能实现?我查看了string包,但没有找到类似getLastXcharacters的函数。

英文:

If I have the string "12121211122" and I want to get the last 3 characters (e.g. "122"), is that possible in Go? I've looked in the string package and didn't see anything like getLastXcharacters.

答案1

得分: 176

你可以在字符串上使用切片表达式来获取最后三个字节。

s      := "12121211122"
first3 := s[0:3]
last3  := s[len(s)-3:]

如果你使用的是 Unicode,可以这样做:

s      := []rune("世界世界世界")
first3 := string(s[0:3])
last3  := string(s[len(s)-3:])

请查看《Go 中的字符串、字节、符文和字符》和《切片技巧》。

英文:

You can use a slice expression on a string to get the last three bytes.

s      := "12121211122"
first3 := s[0:3]
last3  := s[len(s)-3:]

Or if you're using unicode you can do something like:

s      := []rune("世界世界世界")
first3 := string(s[0:3])
last3  := string(s[len(s)-3:])

Check Strings, bytes, runes and characters in Go and Slice Tricks.

答案2

得分: 18

答案取决于你对“字符”一词的理解。如果你指的是字节,则可以使用以下代码:

s := "12121211122"
lastByByte := s[len(s)-3:]

如果你指的是UTF-8编码字符串中的符文(rune),则可以使用以下代码:

s := "12121211122"
j := len(s)
for i := 0; i < 3 && j > 0; i++ {
    _, size := utf8.DecodeLastRuneInString(s[:j])
    j -= size
}
lastByRune := s[j:]

你也可以将字符串转换为[]rune并对符文切片进行操作,但这会分配内存。

英文:

The answer depends on what you mean by "characters". If you mean bytes then:

s := &quot;12121211122&quot;
lastByByte := s[len(s)-3:]

If you mean runes in a utf-8 encoded string, then:

s := &quot;12121211122&quot;
j := len(s)
for i := 0; i &lt; 3 &amp;&amp; j &gt; 0; i++ {
	_, size := utf8.DecodeLastRuneInString(s[:j])
	j -= size
}
lastByRune := s[j:]

You can also convert the string to a []rune and operate on the rune slice, but that allocates memory.

huangapple
  • 本文由 发表于 2014年10月3日 01:55:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/26166641.html
匿名

发表评论

匿名网友

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

确定