OneBite.Dev - Coding blog in a bite size

split a string by empty space in Go

Code snippet on how to split a string by empty space in Go

  package main

import (
	"fmt"
	"strings"
)

func main() {
	str := "This is a sentence"

	// Use 'Split' method to split string with empty space, which returns slice
	splitedString := strings.Split(str, " ")

	// Print the splited slice
	fmt.Printf("%v", splitedString)
}

This code uses the ‘Split’ method to split the given string with empty space and returns a slice of the resulting strings. First, the given string is stored in the variable ‘str’, then the strings package is imported, which contains the ‘Split’ method. ‘Split’ method is used to split the string stored in ‘str’ with empty space. The resulting slice of strings is stored in the variable ‘splitedString’. Finally, the ‘Printf’ method is used to print the ‘splitedString’ slice.

go