The strings
package is a Go standard library package that contains functions to manipulate UTF-8 encoded strings.
HasSuffix()
methodThe 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.
func HasSuffix(s, suffix string) bool
s
and another string suffix
as input. The HasSuffix()
method checks if the input string s
ends with the suffix
string.true
if the string s
ends with the suffix
string and false
otherwise.HasSuffix()
is present in the strings
standard package.true
if we pass an empty string as a suffix string since it is a suffix of all strings.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, ""))}
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.
The program prints below output and exits.
true
false
false
true