How to check if a string starts with a specified Prefix string in Golang?


The HasPrefix() function of string class in Golang is used to check whether a given string begins with a specified Prefix string or not. It returns True if the given string begins with the specified prefix string; otherwise it returns False.

Syntax

func HasPrefix(s, prefix string) bool

Where x is the given string. It returns a Boolean value.

Example

In this example, we are going to use HasPrefix() along with an if condition to check wheter the two defined variables are starting with the same Prefix string or not.

package main
import (
   "fmt"
   "strings"
)
func main() {
   
   // Initializing the Strings
   p := "HasPrefix Function is quite useful."
   q := "Has"

   // Display the Strings
   fmt.Println("String 1:", p)
   fmt.Println("String 2:", q)

   // Using the HasPrefix Function
   if strings.HasPrefix(p, q) == true {
      fmt.Println("Both the strings have the same prefix.")
   } else {
      fmt.Println("The strings don't start with the same prefix.")
   }
}

Output

It will generate the following output −

String 1: HasPrefix Function is quite useful.
String 2: Has
Both the strings have the same prefix.

Example

Let us take another example

package main
import (
   "fmt"
   "strings"
)
func main() {

   // Initializing the Strings
   x := "Go HasPrefix String Function"

   // Display the Strings
   fmt.Println("Given String:", x)

   // Using the HasPrefix Function
   result1 := strings.HasPrefix(x, "Go")
   result2 := strings.HasPrefix(x, "Golang")

   // Display the HasPrefix Output
   fmt.Println("Given String has the prefix 'Go'? :", result1)
   fmt.Println("Given String has the prefix 'Golang'? :", result2)
}

Output

It will generate the following output −

Given String: Go HasPrefix String Function
Given String has the prefix 'Go'? : true
Given String has the prefix 'Golang'? : false

Updated on: 10-Mar-2022

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements