Home ยป Split String by Space in Golang

Split String by Space in Golang

Use the Golang strings.Split() to split the string into substrings using a specified delimiter space. It split a string by space and returns the slice of substrings.

Syntax

func Split(s, sep string) []string

Where,

s = given string

sep = is the delimiter

Returns string array.

In this article, we will discuss how to use strings.Split() function in golang to split a string by space.

Golang Split String by Space using strings.Split()

Golang strings package has a built-in Split method that takes two arguments; a string and a separator or delimiter to split a string.

package main

import (
	"fmt"
	"strings"
)

func main() {

	// Split by WhiteSpace
	s1 := strings.Split("Go Java Python", " ")
	fmt.Println(s1)
        fmt.Println("The length of the slice is:", len(s1))
}
                   

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

Golang strings Split function takes 2 arguments:

  1. string
  2. delimiter ( in our example its a whitespace)

strings.Split() function splits a string by whitespace and returns a slice of substrings ( string array).

The output of the above golang program to split a string by whitespace is:

[Go Java Python]
The length of the slice is: 3

Split String by Space using strings.Fields()

Golang strings package has a built-in Fields function that takes a string as an argument and split a string by whitespace character and returns a slice of the substrings between that separator.

package main

import (
	"fmt"
	"strings"
)

func main() {

	// Use Fields to Split a string by space
	s1 := strings.Fields("Go Java Jquery Python")
	fmt.Println(s1)
	fmt.Println("The length of the slice is:", len(s1))
}

In the above golang program, strings.Fields() function takes a string as input and splits the string by one or more consecutive white space characters and returns a string array.

The output of the above program after splitting a string by space using the Fields() function is:

[Go Java Jquery Python]
The length of the slice is: 4

Cool Tip: How to use strings.cut() function in golang!

Conclusion

I hope the above article on how to split a string by space in golang is helpful to you.

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

Leave a Comment