Example: Fields and FieldsFunc from BYTES Package
Fields splits the slice s around each instance of one or more consecutive white space characters, returning a slice of subslices of s or an empty list if s contains only white space.
FieldsFunc interprets s as a sequence of UTF-8-encoded Unicode code points. It splits the slice s at each run of code points c satisfying f(c) and returns a slice of subslices of s.
Example
package main
import (
"bytes"
"fmt"
"strings"
)
func main() {
fmt.Println("############ Fields #####################\n")
listCountry := []byte(" Australia Canada Japan Germany India")
fmt.Printf("%q",listCountry)
country := bytes.Fields(listCountry)
for index,element := range country{
fmt.Printf("\n%d => %q", index, element)
}
fmt.Println("\n############ FieldsFunc #####################\n")
sentence := []byte("The Go language has built-in facilities, as well as library support, for writing concurrent programs.")
fmt.Printf("%q",sentence)
vowelsSpace := "aeiouy "
chop := bytes.FieldsFunc(sentence, func(r rune) bool {
return strings.ContainsRune(vowelsSpace, r)
})
for index,element := range chop{
fmt.Printf("\n%d => %q", index, element)
}
}
Output
############ Fields #####################
" Australia Canada Japan Germany India"
0 => "Australia"
1 => "Canada"
2 => "Japan"
3 => "Germany"
4 => "India"
############ FieldsFunc #####################
"The Go language has built-in facilities, as well as library support, for writing concurrent programs."
0 => "Th"
1 => "G"
2 => "l"
3 => "ng"
4 => "g"
5 => "h"
6 => "s"
7 => "b"
8 => "lt-"
9 => "n"
10 => "f"
11 => "c"
12 => "l"
13 => "t"
14 => "s,"
15 => "s"
16 => "w"
17 => "ll"
18 => "s"
19 => "l"
20 => "br"
21 => "r"
22 => "s"
23 => "pp"
24 => "rt,"
25 => "f"
26 => "r"
27 => "wr"
28 => "t"
29 => "ng"
30 => "c"
31 => "nc"
32 => "rr"
33 => "nt"
34 => "pr"
35 => "gr"
36 => "ms."
Most Helpful This Week
Find element in a slice and move it to first position?
How to create thumbnail of an image?
How to create a photo gallery in Go?
Regular expression to validate phone number
How to find out element position in slice?
Example of Switch Case with Break in For Loop
How to find the type of the variable by different ways in Golang?
How to find length of Map in Go?
How to append text to a file in Golang?
How to check if a string contains a white space in Golang?