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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26166641/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 16:16:57  来源:igfitidea点击:

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

stringgocharacter

提问by sourcey

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 stringpackage and didn't see anything like getLastXcharacters.

如果我有字符串“12121211122”并且我想获取最后 3 个字符(例如“122”),这在 Go 中可行吗?我查看了string包裹,没有看到类似getLastXcharacters.

回答by OneOfOne

You can use a slice expressionon 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:

或者,如果您使用的是 unicode,则可以执行以下操作:

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

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

在 Goand Slice Tricks 中检查字符串、字节、符文和字符

回答by Simon Fox

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

答案取决于您所说的“字符”是什么意思。如果你的意思是字节,那么:

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

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

如果您的意思是 utf-8 编码字符串中的符文,则:

s := "12121211122"
j := len(s)
for i := 0; i < 3 && j > 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.

您还可以将字符串转换为 []rune 并在 rune 切片上进行操作,但这会分配内存。