To get the last N characters of a given string in Go, you can use string slicing. The syntax to use string slicing on a string str
is str[start:stop]
. Since we need the last N characters, we can specify start=len(str)-N, and stop=default value of length of string.
In this example,
str1
with a string value of "Hello World"
.str1[len(str1)-5:]
to get the last 5 characters.package main
import "fmt"
func main() {
str1 := "Hello World"
last5Chars := str1[len(str1)-5:]
fmt.Println("Last 5 characters of the string are:", last5Chars)
}
Last 5 characters of the string are: World
In this example,
str2
with a string value of "apple"
.str2[len(str2)-3:]
to get the last 3 characters.package main
import "fmt"
func main() {
str2 := "apple"
last3Chars := str2[len(str2)-3:]
fmt.Println("Last 3 characters of the string are:", last3Chars)
}
Last 3 characters of the string are: ple
In this tutorial, we learned How to get Last N Characters in String in Go language with well detailed examples.