strings.HasPrefix() method in Golang

HasPrefix() method is a part of the strings package in the Go language. This post will look at the HasPrefix() method in detail.

  • Method declaration – func HasPrefix(s, prefix string) bool
  • What does it do? It checks whether the string s ( passed in the first argument ) starts with the string prefix ( passed in the second argument ) or not
  • What does it return? It returns true if the string s starts with the string prefix. Otherwise, it will return false

So, if you have to find out whether a string starts from another string or not, then the HasPrefix() method can help you there.

package main

import (
	"fmt"
	"strings"
)

func main() {

	isPrefix := strings.HasPrefix("codekru", "code")

	fmt.Println("Does \"codekru\" starts from \"code\":", isPrefix)

}

Output –

Does "codekru" starts from "code": true
Internal implementation of the HasPrefix() method
func HasPrefix(s, prefix string) bool {
	return len(s) >= len(prefix) && s[0:len(prefix)] == prefix
}

So, what is happening here?

  • First, we are checking whether the length of the given string is greater than or equal to that of the prefix string passed in the arguments. If not, then it will return false then and there only.
  • And, if the length condition passes, we further check whether the specified string from starting point up to the prefix’s string length is equal to the prefix string. And if this condition passes, the function will return true, otherwise false.

The What If scenarios

What if we use an empty string as the prefix string?

It will return true as illustrated by the below program.

package main

import (
	"fmt"
	"strings"
)

func main() {

	isPrefix := strings.HasPrefix("codekru", "")

	fmt.Println("Empty string is the prefix of codekru string?", isPrefix)

}

Output –

Empty string is the prefix of codekru string? true
What if we don’t initialize both of our strings and use the HasPrefix() method on them?

If we don’t initialize a string, it is considered an empty one. So, effectively, we will be using the HasPrefix() method on two empty strings, which eventually will return true, as illustrated by the below example

package main

import (
	"fmt"
	"strings"
)

func main() {

	var str string
	var prefix string

	isPrefix := strings.HasPrefix(str, prefix)

	fmt.Println(isPrefix)

}

Output –

true

Please visit this link to learn more about the Strings in Go language and its other functions or methods.

We hope that you have liked the article. If you have any doubts or concerns, please feel free to write us in the comments or mail us at [email protected]

Related Articles –
Liked the article? Share this on

Leave a Comment

Your email address will not be published.