How to check if a string begins with a prefix in Go
The strings package is a Go standard library package that contains functions to manipulate UTF-8 encoded strings.
The HasPrefix() method
The strings package provides the HasPrefix() method, which can be used to check if a string is a prefix of another string.
This is used to quickly test if one or more characters match at the start of a string, without using a loop.
Syntax
func HasPrefix(s, prefix string) bool
Argument
- This method takes the string
sand another stringprefixas input. TheHasPrefix()method checks ifprefixis a prefix of the input strings.
Return value
- It returns
trueifsbegins withprefix, otherwise it returnsfalse.
Important points
HasPrefix()is present in thestringsstandard package.- It performs case-sensitive comparison.
- It returns
trueif we pass an empty string as a prefix since an empty string is the prefix of all strings.
Code
In the code below, we imported the fmt and strings package to our program.
package mainimport ("fmt""strings")func main() {sourceString := "Educative"fmt.Println(strings.HasPrefix(sourceString, "Ed"))fmt.Println(strings.HasPrefix(sourceString, "ed"))fmt.Println(strings.HasPrefix(sourceString, "ducative"))fmt.Println(strings.HasPrefix(sourceString, ""))}
Explanation
-
We call the
HasPrefix()method with"Educative"as the source string and"Ed"as the prefix to check. This returnstrueas"Ed"is the prefix of"Educative". -
We again call the
HasPrefix()method with"Educative"as the source string and"ed"as the prefix to check. This returnsfalseas"ed"is NOT the prefix of"Educative"because theHasPrefix()method is case sensitive. -
Then we call to
HasPrefix()with"Educative"as the source string and"ducative"as the prefix which returnsfalse. -
At last, we pass
"Educative"as the source and an empty string as the prefix string and it returnstrue. -
We are showing the output of all these operations using the
Println()method of thefmtpackage.
Output
The program prints the output below and exits:
true
false
false
true