0
0
GoHow-ToBeginner · 3 min read

How to Split String in Go: Simple Guide with Examples

In Go, you can split a string using the strings.Split function from the strings package. It takes the string to split and a separator string, returning a slice of substrings.
📐

Syntax

The basic syntax to split a string in Go is:

strings.Split(s string, sep string) []string

Here:

  • s is the original string you want to split.
  • sep is the separator string where the split happens.
  • The function returns a slice of strings containing the parts between separators.
go
package main

import (
	"fmt"
	"strings"
)

func main() {
	s := "apple,banana,cherry"
	parts := strings.Split(s, ",")
	fmt.Println(parts)
}
Output
[apple banana cherry]
💻

Example

This example shows how to split a comma-separated string into parts and print each part on its own line.

go
package main

import (
	"fmt"
	"strings"
)

func main() {
	fruits := "apple,banana,cherry"
	parts := strings.Split(fruits, ",")

	for i, fruit := range parts {
		fmt.Printf("Fruit %d: %s\n", i+1, fruit)
	}
}
Output
Fruit 1: apple Fruit 2: banana Fruit 3: cherry
⚠️

Common Pitfalls

Common mistakes when splitting strings in Go include:

  • Using the wrong separator string, which results in no split.
  • Expecting strings.Split to remove empty strings; it returns empty strings if separators are adjacent.
  • Not importing the strings package.

Example of a common mistake and the correct way:

go
package main

import (
	"fmt"
	"strings"
)

func main() {
	text := "one,,three"

	// Wrong: splitting by space instead of comma
	wrong := strings.Split(text, " ")
	fmt.Println("Wrong split:", wrong)

	// Correct: splitting by comma
	correct := strings.Split(text, ",")
	fmt.Println("Correct split:", correct)
}
Output
Wrong split: [one,,three] Correct split: [one three]
📊

Quick Reference

Summary tips for splitting strings in Go:

  • Use strings.Split to split by a separator.
  • Use strings.SplitN to limit the number of splits.
  • Use strings.Fields to split by any whitespace.
  • Remember to import strings package.

Key Takeaways

Use strings.Split(s, sep) to split a string by a separator in Go.
The function returns a slice of substrings between separators.
Be careful to use the correct separator string to get expected results.
strings.Split includes empty strings if separators are adjacent.
Import the strings package before using split functions.