Home ยป How Split String and Ignore Empty Fields in Golang

How Split String and Ignore Empty Fields in Golang

Use the strings.FieldsFunc() function in golang to split a string based on the given function. The function checks all Unicode code points and returns an array of slices of string.

Syntax

func FieldsFunc(s string, f func(rune) bool) []string

Where,

s = given string

f = function that checks all Unicode code characters.

Returns string array.

In this article, we will discuss how to split a string and ignore empty fields using the strings.FieldsFunc() function.

Golang Split String Ignore Empty Fields Using FieldsFunc

Golang strings package has a built-in FieldsFunc method that takes two arguments; a string and a function that checks all Unicode characters and returns a string array.

package main

import (
	"fmt"
	"strings"
)

func main() {

	// Declare a string
	s1 := "Go,,C#,Java,, Python"
	f := func(c rune) bool {
		return c == ','
	}

	// Use FieldsFunc to split the string based on function
	str := strings.FieldsFunc(s1, f)
	
	// Print the string array
	fmt.Printf("Fields are: %q", str)
	fmt.Println("Length of the string array:", len(str))
}

In the above golang program, it imports strings package to use FieldsFunc and fmt package.

To split the string and ignore empty fields in a string using FieldsFunc, follow the below steps:

  1. Declare string s1
  2. Create a function that checks for Unicode character is equal to comma (,) and returns a value, and assigned it to variable f.
  3. Call the function strings.FieldsFunc(s1, f) to split the string on a comma and ignore the empty field.
  4. Print the string array

The output of the above golang program to split a string and ignore empty fields is:

Fields are: ["Go" "C#" "Java" " Python"]

Length of the string array: 4

Cool Tip: How to split a string into an array in Golang!

Conclusion

I hope the above article on how to split a string to ignore empty fields using FieldsFunc is helpful to you.

You can find more topics about the Golang tutorials on the GolangSpot Home page.

Leave a Comment