How to check if a string ends with a suffix in Go

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

The HasSuffix() method

The strings package provides the HasSuffix() method which checks if a string is a suffix of another string.

This quickly tests for one or more character matches at the string’s end without using a loop.

Syntax

func HasSuffix(s, suffix string) bool

Arguments

  • It takes the string s and another string suffix as input. The HasSuffix() method checks if the input string s ends with the suffix string.

Return value

  • It returns true if the string s ends with the suffix string and false otherwise.

Points to note

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

Code

We imported the fmt and strings package to our program in the code below.

package main
import (
"fmt"
"strings"
)
func main() {
sourceString := "Elephant"
fmt.Println(strings.HasSuffix(sourceString, "ant"))
fmt.Println(strings.HasSuffix(sourceString, "Ant"))
fmt.Println(strings.HasSuffix(sourceString, "test"))
fmt.Println(strings.HasSuffix(sourceString, ""))
}

Explanation

  • We first call the HasSuffix() method with "Elephant" as the source string and "ant" as the suffix to check. This returns true as "ant" is a suffix of "Elephant".

  • We then call the HasSuffix() method again with "Elephant" as source string and "Ant" as the suffix to check. This returns false as "Ant" is not a suffix of "Elephant" since HasSuffix() method is case sensitive.

  • A call to HasSuffix() with "Elephant" as the source string and "test" as suffix returns false.

  • Lastly, we pass "Elephant" as the source and an empty string as suffix string, and it returns true.

We show the output of all these operations using the Println() method of the fmt package.

Output

The program prints below output and exits.

true
false
false
true

Free Resources