Go Reference ยท strings and strconv
Go strings.Split() function
Reference for Go strings.Split, SplitN, SplitAfter and SplitSeq: break a string at a separator, limit the pieces, and handle empty strings and empty separators.
strings.Split(s, sep) cuts s into all the substrings that sit between occurrences of sep and returns them as a []string. The separators are not included in the result.
SplitN limits the number of pieces, SplitAfter keeps the separator at the end of each piece, and SplitSeq (Go 1.24) hands the pieces out one at a time through an iterator instead of building a slice.
parts := strings.Split("a,b,c", ",") // ["a" "b" "c"]
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Syntax
func Split(s, sep string) []string func SplitN(s, sep string, n int) []string func SplitAfter(s, sep string) []string func SplitAfterN(s, sep string, n int) []string func SplitSeq(s, sep string) iter.Seq[string] func SplitAfterSeq(s, sep string) iter.Seq[string]
| Name | Description |
|---|---|
s |
The string to split. |
sep |
The separator. If empty, s is split after each UTF-8 sequence (one piece per rune). |
n |
Maximum number of pieces. n > 0: at most n pieces, the last holds the unsplit rest. n == 0: returns nil. n < 0: all pieces. |
Returns: a slice of pieces (or an iterator for the Seq forms). The slice always has at least one element unless n == 0.
Edge cases:
Split("", ",")returns a slice with one empty string, not an empty slice. Checklencarefully.- Adjacent or trailing separators produce empty strings.
Split(s, "")splits into UTF-8 sequences (runes), not bytes.SplitSeqandSplitAfterSeqneed Go 1.24 or newer.
Usage notes
- Whitespace-separated words? Use
strings.Fields(), which collapses runs of spaces and drops empty pieces.Split(s, " ")on"a b"gives three pieces, one of them empty. - Only the first separator:
strings.Cut()orSplitN(s, sep, 2).Cutis clearer and allocates nothing. - Multiple separators or patterns: use
strings.FieldsFuncorregexp.Split. - CSV and quoted data: do not hand-split; use
encoding/csv, which understands quotes and embedded commas. - Memory: the pieces are substrings of the original and share its memory, so keeping one small piece alive keeps the whole original alive. Use
strings.Clonewhen that matters. - Large inputs:
SplitSeqavoids allocating the result slice when you process each piece once. - Inverse:
strings.Join().