In Go, you can use string slicing to get the first N characters from a string.
In this example,
str
with a string value of "Hello World"
.str[:5]
to get the first 5 characters.package main
import "fmt"
func main() {
str := "Hello World"
first5Chars := str[:5]
fmt.Println("First 5 characters of the string are:", first5Chars)
}
First 5 characters of the string are: Hello
In this example,
str
with a string value of "apple"
.str[:3]
to get the first 3 characters.package main
import "fmt"
func main() {
str := "apple"
first3Chars := str[:3]
fmt.Println("First 3 characters of the string are:", first3Chars)
}
First 3 characters of the string are: app
In this tutorial, we learned How to get First N Characters in String in Go language with well detailed examples.