Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

go
golang
hasprefix
communitycreator
strings

How to check if a string begins with a prefix in Go

Siddharth Singh

The strings package is a Go standard library package that contains functions to manipulate UTF-8 encoded strings.

The HasPrefix() method

The strings package provides the HasPrefix() method, which can be used to check if a string is a prefix of another string.

This is used to quickly test if one or more characters match at the start of a string, without using a loop.

Syntax

func HasPrefix(s, prefix string) bool

Argument

  • This method takes the string s and another string prefix as input. The HasPrefix() method checks if prefix is a prefix of the input string s.

Return value

  • It returns true if s begins with prefix, otherwise it returns false.

Important points

  • HasPrefix() is present in the strings standard package.
  • It performs case-sensitive comparison.
  • It returns true if we pass an empty string as a prefix since an empty string is the prefix of all strings.
Using HasPrefix() to check if a string is a prefix of another string

Code

In the code below, we imported the fmt and strings package to our program.

package main

import (
	"fmt"
	"strings"
)

func main() {
	sourceString := "Educative"
	fmt.Println(strings.HasPrefix(sourceString, "Ed"))
	fmt.Println(strings.HasPrefix(sourceString, "ed"))
	fmt.Println(strings.HasPrefix(sourceString, "ducative"))
	fmt.Println(strings.HasPrefix(sourceString, ""))
}

Explanation

  • We call the HasPrefix() method with "Educative" as the source string and "Ed" as the prefix to check. This returns true as "Ed" is the prefix of "Educative".

  • We again call the HasPrefix() method with "Educative" as the source string and "ed" as the prefix to check. This returns false as "ed" is NOT the prefix of "Educative" because the HasPrefix() method is case sensitive.

  • Then we call to HasPrefix() with "Educative" as the source string and "ducative" as the prefix which returns false.

  • At last, we pass "Educative" as the source and an empty string as the prefix string and it returns true.

  • We are showing the output of all these operations using the Println() method of the fmt package.

Output

The program prints the output below and exits:

true
false
false
true

RELATED TAGS

go
golang
hasprefix
communitycreator
strings
RELATED COURSES

View all Courses

Keep Exploring