Retrieving the Last Characters of a Go String
In Go, a common need arises when working with strings: retrieving the last X characters from a given string. While the string package doesn't provide a specific function for this task, there are efficient ways to accomplish it using slice expressions.
To obtain the last N characters of a string, employ the following slice expression syntax:
stringVariable[len(stringVariable)-N:len(stringVariable)]
For instance, given the string "12121211122" and the desire to retrieve the last three characters ("122"), the expression would be:
s[len(s)-3:len(s)]
This expression retrieves a slice starting at the third character from the end of the string and ending at the end of the string.
Alternatively, if dealing with Unicode characters, one can convert the string to a slice of runes (Unicode code points) using []rune(stringVariable) and execute the same slice expression on the rune slice to obtain the desired characters.
For further reference, consult the resources on Strings, bytes, runes, and characters in Go and Slice Tricks.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3