To get the substring after a specific character in Go, you can use the strings.SplitAfterN
function to get the string after the specified character. strings.SplitAfterN
takes the string, delimiter, and number of splits as arguments, and splits the string by the delimiter into specified number of splits. Since we need the string after the delimiter, we split the string with the specified character or substring as delimiter into two parts. The second part of the split is our required substring.
In this example,
strings
package.str
with a value of "Hello,World"
.strings.SplitAfterN
with ','
as the separator and 2 as the maximum number of splits.package main
import (
"fmt"
"strings"
)
func main() {
str := "Hello,World"
parts := strings.SplitAfterN(str, ",", 2)
fmt.Println("Substring after ',': ", parts[1])
}
Substring after ',': World
In this example,
strings
package.url
with a value of "https://example.com/page"
.strings.SplitAfterN
with '/'
as the separator and 2 as the maximum number of splits.package main
import (
"fmt"
"strings"
)
func main() {
url := "https://example.com/page"
parts := strings.SplitAfterN(url, "/", 2)
fmt.Println("Substring after '/': ", parts[1])
}
Substring after '/': /example.com/page
In this tutorial, we learned how to get Substring after Specific Character in Go language, using strings.SplitAfterN
function, with well detailed examples.