With strings being one of the basic types, learning how to perform various operations becomes essential.
In this guide, you will learn how to check if a string begins with a specified substring or prefix or not.
Strings. HasPrefix()
To check if a string begins with a specific substring, we will use the HasPrefix() method from the strings package.
You will need to import the strings package, as shown in the example import clause below:
Once imported, you can use the methods from the package.
The syntax for the HasPrefix() method is as shown:
The function takes the string and the substring to check as the parameters. The function returns a Boolean true if the string begins with the specified substring. Otherwise, the function returns a Boolean false.
To better understand how the function works, consider the example below:
import (
"fmt"
"strings"
)
func main() {
str_1 := "Hello everyone and welcome to Linuxhint"
str_2 := "Here, you can learn everything tech related."
my_prefix := " "
// check if string starts with a specified prefix
fmt.Println(strings.HasPrefix(str_1, "Hello"))
fmt.Println(strings.HasPrefix(str_2, "Hello"))
fmt.Println(strings.HasPrefix(str_2, "Here"))
fmt.Println(strings.HasPrefix(str_1, "Linuxhint"))
fmt.Println(strings.HasPrefix(str_2, my_prefix))
fmt.Println(strings.HasPrefix(str_1, " "))
}
The example above tests if the strings start with a specified prefix. As you will see, you can specify the prefix value as a string literal or as a variable.
The resulting output is as shown:
false
true
false
false
false
Closing
This guide shows you how to use the strings. HasPrefix() method checks if a string starts with a specified substring.
Thanks for reading!