×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang bytes.TrimSuffix() Function with Examples

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

bytes.TrimSuffix()

The TrimSuffix() function is an inbuilt function of the bytes package which is used to get the byte slice (s) without the provided trailing suffix string. If s doesn't end with suffix, s is returned unchanged.

It accepts two parameters (s, suffix []byte) and returns the byte slice (s) without the provided trailing suffix string. If s doesn't end with suffix.

Syntax

func TrimSuffix(s, suffix []byte) []byte

Parameters

  • s : The byte slice for trimming.
  • suffix : The trailing suffix string to be removed.

Return Value

The return type of the TrimSuffix() function is a []byte, it returns the byte slice (s) without the provided trailing suffix string. If s doesn't end with suffix.

Example 1

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

package main

import (
	"bytes"
	"fmt"
)

func main() {
	fmt.Printf("%q\n", bytes.TrimSuffix(
		[]byte("!!!Hello!!! World.!!!"), []byte("!!!")))
	fmt.Printf("%q\n", bytes.TrimSuffix(
		[]byte("   Hello    World.   "), []byte("   ")))
	fmt.Printf("%q\n", bytes.TrimSuffix(
		[]byte("Hi How are you?"), []byte("you?")))
}

Output:

"!!!Hello!!! World."
"   Hello    World."
"Hi How are "

Example 2

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

package main

import (
	"bytes"
	"fmt"
)

func main() {
	var str []byte
	var suffix []byte
	var result []byte

	str = []byte("!!!Hello!!! World.!!!")
	suffix = []byte("!!!")
	result = bytes.TrimSuffix(str, suffix)
	fmt.Printf("Original string: %q\n", str)
	fmt.Printf("Trimmed string: %q\n", result)
	fmt.Println()

	str = []byte("   Hello    World.   ")
	suffix = []byte("   ")
	result = bytes.TrimSuffix(str, suffix)
	fmt.Printf("Original string: %q\n", str)
	fmt.Printf("Trimmed string: %q\n", result)
	fmt.Println()

	str = []byte("Hi How are you?")
	suffix = []byte(" you?")
	result = bytes.TrimSuffix(str, suffix)
	fmt.Printf("Original string: %q\n", str)
	fmt.Printf("Trimmed string: %q\n", result)
}

Output:

Original string: "!!!Hello!!! World.!!!"
Trimmed string: "!!!Hello!!! World."

Original string: "   Hello    World.   "
Trimmed string: "   Hello    World."

Original string: "Hi How are you?"
Trimmed string: "Hi How are"

Golang bytes Package »




Comments and Discussions!

Load comments ↻





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