HiveBrain v1.2.0
Get Started
← Back to all entries
snippetgoCritical

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
lasthowthegolangcharactersstringget

Problem

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.

Solution

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.

Code Snippets

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

Context

Stack Overflow Q#26166641, score: 189

Revisions (0)

No revisions yet.