HasSuffix() function in the Golang strings package checks if the given string ends with a specified suffix. It returns true if the given string has a specified suffix else returns false.
HasSuffix() Syntax
The syntax for HasSuffix() function is:
func HasSuffix(s1, suffix string) bool
HasSuffix() Parameters
The HasSuffix() function takes two string arguments
s1 is the string
suffix is the string
HasSuffix() Return Value
The strings package HasSuffix() function returns a true value if the given string ends with a specified suffix else returns false.
Let’s understand the string package HasSuffix() method with examples.
strings.HasSuffix() function to check string ends with a suffix
The following go program checks if a string ends with a specified suffix using the strings.HasSuffix() function.
package main import ( "fmt" "strings" ) func main() { fmt.Println(strings.HasSuffix("GolangSpot", "Spot")) fmt.Println(strings.HasSuffix("GolangSpot", "Go")) fmt.Println(strings.HasSuffix("GolangSpot", "")) }
The output of the above program to find string has specified suffix using the HasSuffix() in go is:
true
false
true
In the above program,
The first output has a true value as the given string “GolangSpot” ends with the suffix string “Spot”.
The second output has a false value as the given string “GolangSpot” doesn’t end with the suffix “Go”.
The third output has a true value as the given string “GolangSpot” doesn’t have the suffix “”.
Cool Tip: How to use the string HasPrefix function in Golang!
Conclusion
I hope the above article on the HasSuffix() method to check if the given string ends with a specified suffix is helpful to you.
You can find more topics about the Golang tutorials on the GolangSpot Home page.