×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang bytes.TrimSpace() Function with Examples

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

bytes.TrimSpace()

The TrimSpace() function is an inbuilt function of the bytes package which is used to get a subslice of the byte slice (s) by slicing off all leading and trailing white spaces, as defined by Unicode.

It accepts one parameter (s []byte) and returns a subslice of s by slicing off all leading and trailing white spaces.

Syntax

func TrimSpace(s []byte) []byte

Parameters

  • s : The byte slice for trimming.

Return Value

The return type of the TrimSpace() function is a []byte, it returns a subslice of s by slicing off all leading and trailing white spaces.

Example 1

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

package main

import (
	"bytes"
	"fmt"
)

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

Output:

"Hello, World."
"Hello    World."
"Hi How are you?"

Example 2

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

package main

import (
	"bytes"
	"fmt"
)

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

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

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

	str = []byte("\t\t\n\n  Hi How are you? \t\t\n")
	result = bytes.TrimSpace(str)
	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: "\t\t\n\n  Hi How are you? \t\t\n"
Trimmed string: "Hi How are you?"

Golang bytes Package »




Comments and Discussions!

Load comments ↻





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