Home >Backend Development >Golang >How to Extract the Last X Characters from a Go String?

How to Extract the Last X Characters from a Go String?

Susan Sarandon
Susan SarandonOriginal
2024-11-29 22:27:10802browse

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]
  • start represents the position of the first character to include.
  • end denotes the position of the character immediately after the last character to include (the end character is not included).

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:

  • [Strings, Bytes, Runes, and Characters in Go](https://go.dev/blog/strings)
  • [Slice Tricks](https://go.dev/blog/slices)

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn