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
sand another stringsuffixas input. TheHasSuffix()method checks if the input stringsends with thesuffixstring.
Return value
- It returns
trueif the stringsends with thesuffixstring andfalseotherwise.
Points to note
HasSuffix()is present in thestringsstandard package.- It performs case-sensitive comparison.
- It returns
trueif we pass an empty string as a suffix string since it is a suffix of all strings.
Code
We imported the fmt and strings package to our program in the code below.
package mainimport ("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 returnstrueas"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 returnsfalseas"Ant"is not a suffix of"Elephant"sinceHasSuffix()method is case sensitive. -
A call to
HasSuffix()with"Elephant"as the source string and"test"as suffix returnsfalse. -
Lastly, we pass
"Elephant"as the source and an empty string as suffix string, and it returnstrue.
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