Golang bytes.HasSuffix() Function with Examples

Golang | bytes.HasSuffix() Function: Here, we are going to learn about the HasSuffix() function of the bytes package with its usages, syntax, and examples.
Submitted by IncludeHelp, on September 23, 2021

bytes.HasSuffix()

The HasSuffix() function is an inbuilt function of the bytes package which is used to check whether the byte slice s ends with suffix.

It accepts two parameters (s, suffix []byte) and returns true if the byte slice ends with suffix; false, otherwise.

Syntax:

func HasSuffix(s, suffix []byte) bool

Parameter(s):

  • s : The byte slice to be checked whether it is ended with a suffix or not.
  • suffix : The byte slice to be checked.

Return Value:

The return type of the bytes.HasSuffix() function is a bool, it returns true if the byte slice ends with suffix; false, otherwise.

Example 1:

// Golang program to demonstrate the
// example of bytes.HasSuffix() function

package main

import (
	"bytes"
	"fmt"
)

func main() {
	fmt.Println(bytes.HasSuffix(
		[]byte("Hi! How are you"), []byte("you")))
	fmt.Println(bytes.HasSuffix(
		[]byte("Hi! How are you"), []byte("you?")))
	fmt.Println(bytes.HasSuffix(
		[]byte("Hi! How are you"), []byte(" you")))
}

Output:

true
false
true

Example 2:

// Golang program to demonstrate the
// example of bytes.HasSuffix() function

package main

import (
	"bytes"
	"fmt"
)

func main() {
	var str string
	var suffix string

	str = "Hi there!"
	suffix = "!"

	if bytes.HasSuffix([]byte(str), []byte(suffix)) == true {
		fmt.Printf("Yes, %q ends with %q\n", str, suffix)
	} else {
		fmt.Printf("No, %q does not end with %q\n", str, suffix)
	}

	str = "Aspire to inspire before we expire."
	suffix = "expire."

	if bytes.HasSuffix([]byte(str), []byte(suffix)) == true {
		fmt.Printf("Yes, %q ends with %q\n", str, suffix)
	} else {
		fmt.Printf("No, %q does not end with %q\n", str, suffix)
	}

	str = "Aspire to inspire before we expire."
	suffix = "expire"

	if bytes.HasSuffix([]byte(str), []byte(suffix)) == true {
		fmt.Printf("Yes, %q ends with %q\n", str, suffix)
	} else {
		fmt.Printf("No, %q does not end with %q\n", str, suffix)
	}
}

Output:

Yes, "Hi there!" ends with "!"
Yes, "Aspire to inspire before we expire." ends with "expire."
No, "Aspire to inspire before we expire." does not end with "expire"

Golang bytes Package »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.