Home >Backend Development >Golang >How to Extract the Last X Characters from a Go String?
Getting the Last X Characters of a Go String
Question: How can one extract the last X characters from a string in Go? For instance, given the string "12121211122", is it possible to retrieve the last three characters ("122")?
Answer: Yes, it is possible to obtain the final X characters of a string in Go. This can be achieved through the use of slice expressions.
Using Slice Expressions
A slice expression enables the creation of a new string by selecting a range of characters from an existing string. The syntax is:
string[start:end]
Example for Last 3 Characters
To retrieve the last three characters of a string, use the following expression:
string[len(string)-3:]
This expression specifies that we want to begin at a position three characters before the end of the string (i.e., len(string)-3) and include all characters to the end.
Unicode Support
For strings that contain Unicode characters, it is advisable to use runes instead of bytes. Runes represent Unicode code points, ensuring that full characters are treated as single entities.
Example for Last 3 Characters in Unicode
To obtain the last three characters of a Unicode string, use:
stringRune := []rune(string) first3 := string(stringRune[0:3]) last3 := string(stringRune[len(stringRune)-3:])
This converts the string to a slice of runes (stringRune), then extracts the first three and last three characters by slicing the rune array.
Additional Resources
Refer to the following resources for further information:
The above is the detailed content of How to Extract the Last X Characters from a Go String?. For more information, please follow other related articles on the PHP Chinese website!