Go – Check if String ends with Suffix

To check if a string ends with a given suffix string in Go language, call HasSuffix function of strings package, and pass the string and suffix string as arguments to it.

The syntax to check if string str ends with suffix string suffix using HasSuffix function is

</>
Copy
strings.HasSuffix(str, suffix)

HasSuffix function returns a boolean value. It returns true if string str ends with string suffix.

Examples

In the following example, we take two strings, str and suffix, and check if str ends with suffix using HasSuffix function.

example.go

</>
Copy
package main

import (
	"fmt"
	"strings"
)

func main() {
	str := "Hello World"
	suffix := "World"
	if strings.HasSuffix(str, suffix) {
		fmt.Println("The string ends with given suffix.")
	} else {
		fmt.Println("The string does not end with given suffix.")
	}
}

Output

The string ends with given suffix.

Conclusion

In this Golang Tutorial, we learned how to check if a string ends with a given suffix string in Go programming language, with the help of example programs.