英文:
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 := "12121211122"
lastByByte := s[len(s)-3:]
If you mean runes in a utf-8 encoded string, then:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论