×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang bytes.TrimPrefix() Function with Examples

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

bytes.TrimPrefix()

The TrimPrefix() function is an inbuilt function of the bytes package which is used to get the byte slice (s) without the provided leading prefix string. If the byte slice (s) doesn't start with prefix, s is returned unchanged.

It accepts two parameters (s, prefix []byte) and returns s without the provided leading prefix string.

Syntax

func TrimPrefix(s, prefix []byte) []byte

Parameters

  • s : The byte slice for trimming.
  • prefix : The leading prefix string to be removed.

Return Value

The return type of the TrimPrefix() function is a []byte, it returns s without the provided leading prefix string.

Example 1

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

package main

import (
	"bytes"
	"fmt"
)

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

Output:

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

Example 2

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

package main

import (
	"bytes"
	"fmt"
)

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

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

	str = []byte("   Hello    World.   ")
	prefix = []byte("   ")
	result = bytes.TrimPrefix(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 = []byte("Hi ")
	result = bytes.TrimPrefix(str, prefix)
	fmt.Printf("Original string: %q\n", str)
	fmt.Printf("Trimmed string: %q\n", result)
}

Output:

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

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

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

Golang bytes Package »




Comments and Discussions!

Load comments ↻





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