Home » Golang String HasPrefix() Function

Golang String HasPrefix() Function

HasPrefix() function in the Golang strings package checks if the given string begins with a specified prefix. It returns true if the given string has a specified prefix else returns false.

HasPrefix() Syntax

The syntax for HasPrefix() function is:

func HasPrefix(s1, prefix string) bool

HasPrefix() Parameters:

The HasPrefix() function takes two string arguments

s1 is the string

the prefix is the string

HasPrefix() Return Value

The strings package HasPrefix() function returns a true value if the given string starts with a specified prefix else returns false.

Let’s understand the string package HasPrefix() method with examples.

strings.HasPrefix() function to check string starts with prefix

The following go program checks if a string begins with a specified prefix using the strings.HasPrefix() function.

package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Println(strings.HasPrefix("GolangSpot", "Go"))
	fmt.Println(strings.HasPrefix("GolangSpot", "Spot"))
	fmt.Println(strings.HasPrefix("GolangSpot", ""))
}

The output of the above program to find string has specified prefix using the HasPrefix() in go is:

true
false
true

In the above program,

The first output has a true value as the given string “GolangSpot” begins with the prefix “Go”.

The second output has a false value as the given string “GolangSpot” doesn’t start with the prefix “Spot”.

The third output has a true value as the given string “GolangSpot” doesn’t have the prefix “”.

Cool Tip: How to use the string Cut function in Golang!

Conclusion

I hope the above article on the HasPrefix() method to check if the given string begins with a specified prefix is helpful to you.

You can find more topics about the Golang tutorials on the GolangSpot Home page.

Leave a Comment