How to Split String in Golang

To split a string in Go, you can use the strings.Split() function that takes two arguments: the string you want to split and the delimiter on which you want to split the string.

Example

package main

import (
  "fmt"
  "strings"
)

func main() {
  // Define a string to split
  text := "John-wick-4-is-awesome"

  // Split the string using the "-" delimiter
  words := strings.Split(text, "-")

  // Print the split words
  fmt.Println(words)
}

Output

[John wick 4 is awesome]

The output is a slice of strings, which you can access or iterate through as needed. For example, you can print the individual words using a for loop with the range keyword.

package main

import (
  "fmt"
  "strings"
)

func main() {
  // Define a string to split
  text := "John-wick-4-is-awesome"

  // Split the string using the "-" delimiter
  words := strings.Split(text, "-")

  // Print the individual words
  for index, word := range words {
    fmt.Printf("Word %d: %s\n", index+1, word)
  }
}

Output

Word 1: John
Word 2: wick
Word 3: 4
Word 4: is
Word 5: awesome

That’s it.

Leave a Comment