To get the substring between two specific characters in Go, you can use the strings.Index
function to find the indices of the specified characters and then extract the substring using slicing with the found indices.
In this example,
str
with a value of "Hello,ABC! Welcome to our world."
.strings.Index
function to find the indices of ','
and '!'
.package main
import (
"fmt"
"strings"
)
func main() {
str := "Hello,ABC! Welcome to our world."
start := strings.Index(str, ",") + 1
end := strings.Index(str, "!")
substring := str[start:end]
fmt.Println("Substring between ',' and '!':", substring)
}
Substring between ',' and '!': World
In this example,
url
with a value of "https://example.com/page?query=1"
.strings.Index
function to find the indices of '/'
and '?'
.package main
import (
"fmt"
"strings"
)
func main() {
url := "https://example.com/page?query=1"
start := strings.Index(url, "/") + 1
end := strings.Index(url, "?")
substring := url[start:end]
fmt.Println("Substring between '/' and '?':", substring)
}
Substring between '/' and '?': /example.com/page
In this tutorial, we learned how to get the Substring between two Specific Characters in Go language, using strings.Index
function and string slicing, with well detailed examples.