AppDividend
Latest Code Tutorials

Golang String Fields: How To Split String In Golang

0

One or more space characters separate a field. The Fields() method in the strings package separates these into an array. It splits into groups of spaces. With Fields() function, we treat many consecutive delimiter characters as one. So several spaces are the same as a single space.

Golang String Fields()

Golang string Fields() is a built-in function that splits a string into substrings removing any space characters, including newlines. The Fields() function accepts a string as an argument and returns an array.

If you want to use Fields() function, then first, you have to import the strings function and then use strings.Fields() function.

Syntax

func Fields(s string) []string

Parameters

The Fields() function takes the string as a parameter, which we need to splits.

Example of Fields() Function

See the following code.

// hello.go

package main

import (
	"fmt"
	"strings"
)

func main() {
	quibi := " TheStranger 50StatesOfFright    MostDangerousGame  "
	series := strings.Fields(quibi)

	// Display all fields, first field and count.
	fmt.Println(series)
	fmt.Println(series[0])
	fmt.Println(len(series))
}

Output

go run hello.go
[TheStranger 50StatesOfFright MostDangerousGame]
TheStranger
3

In the above code, we have defined one string called quibi, which has three fields and spaces.

The strings.Fields() function removes the spaces and converts the string into an array.

Then we have printed the array series, its first element, and the length of the array.

Conclusion

In Golang strings, you are allowed to split a string into a slice using strings.Fields() function.

The Fields() function breaks the string around each instance of consecutive white space characters into an Array.

See also

Golang String Contains()

Golang String to Int

Golang String to int64

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.