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

StringGoCharacter

String Problem Overview


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.

String Solutions


Solution 1 - String

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.

Solution 2 - String

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsourceyView Question on Stackoverflow
Solution 1 - StringOneOfOneView Answer on Stackoverflow
Solution 2 - StringSimon FoxView Answer on Stackoverflow