August 30, 2025
Go lang, get sub string
If you want to get sub string from a string so you can easily do this by getting slice of bytes in Go lang. In Go lang, there is no built-in Substring function like in Java (str.substring) or any other language. Instead, Go relies on slice technique. Slice technique required two parameters in squire brackets using string object, first is the starting index from where we need string, and second parameter indicate how many character you want to retrieve, this second parameter is optional if you do not pass second parameter then it consider you required all the characters from the given index (first parameter). example is mentioned below:
Code
package main
import (
"fmt"
)
func main() {
str := "Hello, Go Programmers"
// From index 0 to 5 (not including 5)
sub_string1 := str[0:5]
fmt.Println(sub_string1) // print: Hello
// From index 10 to end
sub_string2 := str[10:]
fmt.Println(sub_string2) // print: Programmers
// From start to index 5
sub_string3 := str[:5]
fmt.Println(sub_string3) // print: Hello
}