Welcome To Golang By Example

Menu
  • Home
  • Blog
Menu

Check if string begins with a prefix in Go (Golang)

Posted on March 11, 2023March 11, 2023 by admin

Table of Contents

  • Overview
  • Code:

Overview

In GO string are UTF-8 encoded. strings package of GO provides a HasPrefix method that can be used to check if a string begins with a certain prefix

Below is the signature of the function

func HasPrefix(s, prefix string) bool

Let’s look at the working code

Code:

package main
import (
"fmt"
"strings"
)
func main() {
//Input string contains the prefix
res := strings.HasPrefix("abcdef", "ab")
fmt.Println(res)
//Input string doesn't contain the prefix
res = strings.HasPrefix("abcdef", "ac")
fmt.Println(res)
}

Output:

true
false

Recent Posts

  • Check if a string ends with a suffix in Go (Golang)
  • Check if string begins with a prefix in Go (Golang)
  • Join a string by delimiter or a separator in Go (Golang)
  • Get all words from a sentence in GO (Golang)
  • Split a string in Go(Golang)
©2023 Welcome To Golang By Example | Design: Web XP