Go – Check if String starts with Prefix
To check if a string starts with a given prefix string in Go language, call HasPrefix
function of strings
package, and pass the string and prefix string as arguments to it.
The syntax to check if string str
starts with prefix string prefix
using HasPrefix
function is
</>
Copy
strings.HasPrefix(str, prefix)
HasPrefix function returns a boolean value. It returns true if string str
starts with string prefix
.
Examples
In the following example, we take two strings, str
and prefix
, and check if str
starts with prefix
using HasPrefix
function.
example.go
</>
Copy
package main
import (
"fmt"
"strings"
)
func main() {
str := "Hello World!"
prefix := "Hello"
if strings.HasPrefix(str, prefix) {
fmt.Println("The string starts with given prefix.")
} else {
fmt.Println("The string does not start with given prefix.")
}
}
Output
The string starts with given prefix.
Conclusion
In this Golang Tutorial, we learned how to check if a string starts with a given prefix string in Go programming language, with the help of example programs.