How to use the Fields() function in Golang?

Go ProgrammingServer Side ProgrammingProgramming

The strings package of Golang provides a Fields() method, which can be used to split a string around one or more instances of consecutive whitespace characters.

The Fields() function splits a given string into substrings by removing any space characters, including newlines. And it treats multiple consecutive spaces as a single space.

Syntax

func Fields(s string) []string

Where s is the string parameter.

Example

Let us consider the following example −

package main
import (
   "fmt"
   "strings"
)
func main() {

   // Initializing the Strings
   string1 := " The Golang Programming Language "

   // Display the Strings
   fmt.Println("Input String:", string1)

   // Using the EqualFold Function
   m := strings.Fields(string1)

   // Display the Fields Output
   fmt.Println("Output String: ", m)
}

Output

On execution, it will produce the following output −

Input String: The Golang Programming Language
Output String: [The Golang Programming Language]

Here we used the Fields() function to remove the additional spaces between the words in the given input string.

Example

In this example, we are going to see how the newlines special characters are removed using the Fields function.

package main
import (
   "fmt"
   "strings"
)
func main() {

   // Initializing the Strings
   x := "Welcome \n to \n Golang \n Language \n"
   y := "Programming \n Language \n"
   z := "Object \n Oriented \n Programming \n Language \n"
   w := "Golang \n Programming \n Language \n"

   // Display the Strings
   fmt.Println("Input String 1:", x)
   fmt.Println("Input String 2:", y)
   fmt.Println("Input String 3:", z)
   fmt.Println("Input String 4:", w)

   // Using the EqualFold Function
   m := strings.Fields(x)
   n := strings.Fields(y)
   o := strings.Fields(z)
   p := strings.Fields(w)

   // Display the Fields Output
   fmt.Println("Output String 1: ", m)
   fmt.Println("Output String 2: ", n)
   fmt.Println("Output String 3: ", o)
   fmt.Println("Output String 4: ", p)
}

Output

It will generate the following output −

Input String 1: Welcome
to
Golang
Language

Input String 2: Programming
Language

Input String 3: Object
Oriented
Programming
Language

Input String 4: Golang
Programming
Language

Output String 1: [Welcome to Golang Language]
Output String 2: [Programming Language]
Output String 3: [Object Oriented Programming Language]
Output String 4: [Golang Programming Language]
raja
Updated on 10-Mar-2022 07:08:43

Advertisements