In this shot, we will learn how to check if a string starts with a specified string in Golang
.
We can use the HasPrefix
function, provided by the strings
package, to check if a string starts with some other string.
strings.HasPrefix("string","prefix string")
This function accepts two parameters:
This function returns True
if the string starts with the provided prefix string. Otherwise, it returns False
.
If the string from the first parameter starts with the prefix string in the second parameter, then the function returns True
. If the string from the first parameter does not start with the prefix string in the second parameter, then HasPrefix
returns False
.
In the following example, we will check to see if the string Hello from educative
starts with Hello
or from
.
Let’s look at the code given below.
package main//import packagesimport("fmt""strings")//program execution starts herefunc main(){//declare stringstr := "Hello from educative"//provide first prefix stringprefstr1 := "Hello"//check if str starts with prefstr1fmt.Println("str starts with ",prefstr1," :",strings.HasPrefix(str, prefstr1))//provide second prefix stringprefstr2 := "from"//check if str starts with prefstr2fmt.Println("str starts with ",prefstr2," :",strings.HasPrefix(str, prefstr2))}
In the code snippet above:
In line 5, we import the format package fmt
, which is used to format the input and output.
In line 6, we import the strings package strings
, which has the HasPrefix
function.
In line 10, the program execution starts from the main()
function in Golang.
In line 12, we declare and initialize the string str
.
In line 15, we declare a substring prefstr1
.
In line 18, we check to see if the string str
starts with the substring prefstr1
, and then we print the returned result.
In line 21, we declare a substring prefstr2
.
In line 24, we check to see if the string str
starts with the substring prefstr2
, and then we print the returned result.