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.
The above is the detailed content of How to Efficiently Retrieve the Last Characters of a Go String?. For more information, please follow other related articles on the PHP Chinese website!