To get the substring before a specific character in Go, you can use the strings.Split
function along with array indexing. The strings.Split
function takes the string and delimiter as arguments, and splits the string by the delimiter. Pass the given string as the first argument, and the specific character as the delimiter string. After the split is done, the first element of the returned array is our required substring.
In this example,
url
with a value of "https://example.com/page"
.strings.Split
function with '/' as the separator to split the string.package main
import (
"fmt"
"strings"
)
func main() {
url := "https://example.com/page"
parts := strings.Split(url, "/")
fmt.Println("Substring before '/':", parts[0])
}
Substring before '/': https:
In this example,
str
with a value of "Hello,World"
.strings.Split
function with ',' as the separator to split the string.package main
import (
"fmt"
"strings"
)
func main() {
str := "Hello,World"
parts := strings.Split(str, ",")
fmt.Println("Substring before ',':", parts[0])
}
Substring before ',': Hello
In this tutorial, we learned how to get Substring before a Specific Character in Go language, using strings.Split
function, with well detailed examples.