How to Check If the String Starts with Specified Prefix in Golang

To check if a string starts with a specified Prefix string in Golang, you can use the “HasPrefix()” function. The HasPrefix() function is “used to check whether a given string begins with a specified Prefix string.” It returns True if the given string begins with the specified prefix string; otherwise, it returns False.

Syntax

func HasPrefix(s, prefix string) bool

Parameters

s:  It is the given string.

Return value

It returns a Boolean value.

Example 1

package main

import (
  "fmt"
  "strings"
)

// Main function
func main() {

  // Creating and initializing strings
  s1 := "Programming in Go is rewarding."
  s2 := "Go is a statically typed language."
  s3 := "OpenAI is advancing AI research."

  // Checking if the given strings start with the specified prefixes
  // Using HasPrefix() function
  res1 := strings.HasPrefix(s1, "Programming")
  res2 := strings.HasPrefix(s1, "Coding")
  res3 := strings.HasPrefix(s2, "Go")
  res4 := strings.HasPrefix(s2, "Python")
  res5 := strings.HasPrefix(s3, "OpenAI")
  res6 := strings.HasPrefix(s3, "ClosedAI")

  // Displaying results
  fmt.Println("Does String 1 start with 'Programming'? ", res1)
  fmt.Println("Does String 1 start with 'Coding'? ", res2)
  fmt.Println("Does String 2 start with 'Go'? ", res3)
  fmt.Println("Does String 2 start with 'Python'? ", res4)
  fmt.Println("Does String 3 start with 'OpenAI'? ", res5)
  fmt.Println("Does String 3 start with 'ClosedAI'? ", res6)
}

Output

How to Check If the String Starts with Specified Prefix in Golang

Example 2

package main

import (
  "fmt"
  "strings"
)

func main() {

  // Initializing the Strings
  y := "Learning Go is a great experience!"

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

  // Using the HasPrefix Function
  result1 := strings.HasPrefix(y, "Learning")
  result2 := strings.HasPrefix(y, "Studying")

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

Output

Given String: Learning Go is a great experience!
Given String has the prefix 'Learning'? : true
Given String has the prefix 'Studying'? : false

That’s it!

Related posts

Check If String is Alphanumeric in Golang

Trim a String in Golang

Check If String is Empty in Golang

Check If the String Ends with Specified Suffix in Golang

Leave a Comment