Golang bytes.TrimRight() Function with Examples

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

bytes.TrimRight()

The TrimRight() function is an inbuilt function of the bytes package which is used to get a subslice of the byte (s) by slicing off all trailing UTF-8-encoded code points that are contained in the string (cutset).

It accepts two parameters (s []byte, cutset string) and returns a subslice of s by slicing off all trailing UTF-8-encoded code points that are contained in the cutset.

Syntax:

func TrimRight(s []byte, cutset string) []byte

Parameter(s):

  • s : The byte slice for trimming.
  • cutset : The string which contains the characters to be removed.

Return Value:

The return type of the TrimRight() function is a []byte, it returns a subslice of s by slicing off all trailing UTF-8-encoded code points that are contained in the cutset.

Example 1:

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

package main

import (
	"bytes"
	"fmt"
)

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

Output:

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

Example 2:

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

package main

import (
	"bytes"
	"fmt"
)

func main() {
	var str []byte
	var prefix string
	var result []byte

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

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

	str = []byte("Hi How are you?")
	prefix = "?"
	result = bytes.TrimRight(str, prefix)
	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 you"

Golang bytes Package »




Comments and Discussions!

Load comments ↻





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