How to check if a string starts with another given string in Go

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.

Syntax

strings.HasPrefix("string","prefix string")

Parameters

This function accepts two parameters:

  1. The original string that we want to check to see if it starts with the prefix string.
  2. The string that we check to see if it acts as the prefix to the string in the first parameter.

Return value

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.

Example

In the following example, we will check to see if the string Hello from educative starts with Hello or from.

Code

Let’s look at the code given below.

package main
//import packages
import(
"fmt"
"strings"
)
//program execution starts here
func main(){
//declare string
str := "Hello from educative"
//provide first prefix string
prefstr1 := "Hello"
//check if str starts with prefstr1
fmt.Println("str starts with ",prefstr1," :",strings.HasPrefix(str, prefstr1))
//provide second prefix string
prefstr2 := "from"
//check if str starts with prefstr2
fmt.Println("str starts with ",prefstr2," :",strings.HasPrefix(str, prefstr2))
}

Code explanation

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.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources