The strings
package is a Go standard library package that contains functions to manipulate UTF-8 encoded strings.
HasPrefix()
methodThe 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.
func HasPrefix(s, prefix string) bool
s
and another string prefix
as input. The HasPrefix()
method checks if prefix
is a prefix of the input string s
.true
if s
begins with prefix
, otherwise it returns false
.HasPrefix()
is present in the strings
standard package.true
if we pass an empty string as a prefix since an empty string is the prefix of all strings.In the code below, we imported the fmt
and strings
package to our program.
package main import ( "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, "")) }
We call the HasPrefix()
method with "Educative"
as the source string and "Ed"
as the prefix to check. This returns true
as "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 returns false
as "ed"
is NOT the prefix of "Educative"
because the HasPrefix()
method is case sensitive.
Then we call to HasPrefix()
with "Educative"
as the source string and "ducative"
as the prefix which returns false
.
At last, we pass "Educative"
as the source and an empty string as the prefix string and it returns true
.
We are showing the output of all these operations using the Println()
method of the fmt
package.
The program prints the output below and exits:
true
false
false
true
RELATED TAGS
CONTRIBUTOR
View all Courses