HasPrefix()

Published Aug 29, 2023
Contribute to Docs

The HasPrefix() function returns a boolean value indicating whether a given string begins with a given prefix. The method returns true if the string begins with the prefix, otherwise it returns false.

Syntax

strings.HasPrefix(str, prefix)

Where str is the string where we want to check the prefix and prefix is the prefix to be checked.

Example

The following code demonstrate the use of the strings.HasPrefix() function.

package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(strings.HasPrefix("codecademy","code"))
fmt.Println(strings.HasPrefix("GitHub","Hub"))
}

The output will be:

true
false

Codebyte Example

The following example is runnable and uses the strings.HasPrefix() function to determine if codecademy begins with code.

us
Visit us
code
Hide code
Code
Output
Hide output
Hide output
Loading...

All contributors

Looking to contribute?

Learn Go on Codecademy