How to Split a String on Whitespace in Go

To split a string on whitespace characters (spaces, tabs, and newlines) in Go, you can use the strings.Fields() function from the strings package. 

package main

import (

func main() {
  input := "This is John Wick"

  words := strings.Fields(input)

  fmt.Println("Words in the input string:")
  for i, word := range words {
    fmt.Printf("Word %d: %s\n", i+1, word)


Words in the input string:
Word 1: This
Word 2: is
Word 3: John
Word 4: Wick

In this code example, we used strings.Fields() function to split the input string on whitespace characters.

The words variable will hold a slice of strings containing the individual words from the input string.

The strings.Fields() function splits the input string based on any whitespace character, including spaces, tabs, and newlines.

That’s it.

Leave a Comment