×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang bytes.Fields() Function with Examples

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

bytes.Fields()

The Fields() function is an inbuilt function of the bytes package which is used to split the given byte slice s around each instance of one or more consecutive white space characters, as defined by unicode.IsSpace() and returns a slice of subslices of s or an empty slice if s contains only white space.

It accepts one parameter (s []byte) and returns a slice of subslices of s or an empty slice if s contains only white space.

Syntax

func Fields(s []byte) [][]byte

Parameters

  • s : The byte slice to be split into a slice of subslices.

Return Value

The return type of the bytes.Fields() function is a [][]byte, it returns a slice of subslices of s or an empty slice if s contains only white space.

Example 1

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

package main

import (
	"bytes"
	"fmt"
)

func main() {
	fmt.Println(bytes.Fields([]byte("New Delhi India")))
	fmt.Printf("%q\n", bytes.Fields([]byte("New Delhi India")))
	fmt.Println()

	fmt.Println(bytes.Fields([]byte("Hi buddy! How're you?")))
	fmt.Printf("%q\n", bytes.Fields([]byte("Hi buddy! How're you?")))
	fmt.Println()
}

Output:

[[78 101 119] [68 101 108 104 105] [73 110 100 105 97]]
["New" "Delhi" "India"]

[[72 105] [98 117 100 100 121 33] [72 111 119 39 114 101] [121 111 117 63]]
["Hi" "buddy!" "How're" "you?"]

Example 2

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

package main

import (
	"bytes"
	"fmt"
)

func main() {
	fmt.Printf("Fields: %q\n",
		bytes.Fields([]byte("Lean Go Language")))
	fmt.Printf("Fields: %q\n",
		bytes.Fields([]byte("   Lean Go Language   ")))
	fmt.Printf("Fields: %q\n",
		bytes.Fields([]byte("Lean\tGo\tLanguage")))
	fmt.Printf("Fields: %q\n",
		bytes.Fields([]byte("Lean\nGo\nLanguage")))
	fmt.Printf("Fields: %q\n",
		bytes.Fields([]byte("C C++ Go Python")))
}

Output:

Fields: ["Lean" "Go" "Language"]
Fields: ["Lean" "Go" "Language"]
Fields: ["Lean" "Go" "Language"]
Fields: ["Lean" "Go" "Language"]
Fields: ["C" "C++" "Go" "Python"]

Golang bytes Package »




Comments and Discussions!

Load comments ↻





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