How to check if a string ends with a specified Suffix string in Golang?


The HasSuffix() function of string class in Golang is used to check whether a given string ends with a specified Suffix string or not. It returns True if the given string ends with the specified Suffix string; otherwise it returns False.

HasSuffix() and HasPrefix() check if a string ends or starts with a particular set of characters, respectively.

Syntax

func HasSuffix(s, prefix string) bool

Where x is the given string. It returns a Boolean value.

Example 1

In this example, we are going to use HasSuffix() with an if condition to check wheter two defined string variables are ending with the same set of characters or not.

package main
import (
   "fmt"
   "strings"
)
func main() {

   // Initializing the Strings
   m := "HasSuffix String"
   n := "String"

   // Display the Strings
   fmt.Println("String 1: ", m)
   fmt.Println("String 2: ", n)

   // Using the HasSuffix Function
   if strings.HasSuffix(m, n) == true {
      fmt.Println("Both the strings have the same suffix.")
   } else {
      fmt.Println("Strings do not end with the same suffix.")
   }
}

Output

It will generate the following output −

String 1: HasSuffix String
String 2: String
Both the strings have the same suffix.

Example 2

Now, let's take another example of HasSuffix().

package main
import (
   "fmt"
   "strings"
)
func main() {

   // Initializing the Strings
   y := "HasSuffix String Function"

   // Display the Strings
   fmt.Println("Given String:", y)

   // Using the HasSuffix Function
   test1 := strings.HasSuffix(y, "Function")
   test2 := strings.HasSuffix(y, "String")

   // Display the HasSuffix Output
   fmt.Println("The Given String has the Suffix 'Function'? :", test1)
   fmt.Println("The Given String has the Suffix 'String'? :", test2)
}

Output

It will generate the following output −

Given String: HasSuffix String Function
The Given String has the Suffix 'Function'? : true
The Given String has the Suffix 'String'? : false

Updated on: 10-Mar-2022

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements