Go – Split String
To split a string in Go, use the strings.Split() function with the source string and a separator. The function returns the resulting parts as a slice of strings.
This tutorial explains how to split a Go string by a delimiter, comma, space, newline, or a limited number of separators. It also covers empty separators, missing delimiters, whitespace-aware splitting, and common mistakes.
Syntax of strings.Split() in Go
The syntax of strings.Split() is:
strings.Split(str, sep_string)
where
stringsis the package.Splitis the function name.stris the input string.sep_stringis the delimiter or separator.
strings.Split() returns a value of type []string. Import the strings package before calling the function.
Split a Go String by Hyphen
In the following program, we take a string str and split it with hyphen - as delimiter.
example.go
package main
import (
"fmt"
"strings"
)
func main() {
var str = "a-b-c"
var delimiter = "-"
var parts = strings.Split(str, delimiter)
fmt.Println(parts)
}
Output
[a b c]
The separator itself is not included in the returned slice. Here, the two hyphens divide the input into three elements: a, b, and c.
Split a Comma-Separated String in Go
In the following program, we will take a string containing values separated by comma. And we will split this string with comma , as delimiter.
example.go
package main
import (
"fmt"
"strings"
)
func main() {
var str = "a,b,c"
var delimiter = ","
var parts = strings.Split(str, delimiter)
fmt.Println(parts)
}
Output
[a b c]
When comma-separated data contains spaces after each comma, splitting by "," preserves those spaces. You can remove them from each element with strings.TrimSpace().
package main
import (
"fmt"
"strings"
)
func main() {
values := strings.Split("red, green, blue", ",")
for i, value := range values {
values[i] = strings.TrimSpace(value)
}
fmt.Println(values)
}
Output
[red green blue]
Split a Go String by Spaces
To split a string at every literal space, pass " " to strings.Split().
package main
import (
"fmt"
"strings"
)
func main() {
text := "Go makes string handling simple"
words := strings.Split(text, " ")
fmt.Println(words)
}
Output
[Go makes string handling simple]
A literal-space separator treats each space as significant. Consecutive spaces therefore produce empty elements in the result.
package main
import (
"fmt"
"strings"
)
func main() {
words := strings.Split("Go language", " ")
fmt.Printf("%q\n", words)
}
Output
["Go" "" "language"]
Use strings.Fields() for Flexible Whitespace Splitting
Use strings.Fields() when the input may contain multiple spaces, tabs, or newline characters. It splits around one or more consecutive Unicode whitespace characters and does not return empty elements.
package main
import (
"fmt"
"strings"
)
func main() {
text := "Go supports\ttabs\nand newlines"
words := strings.Fields(text)
fmt.Println(words)
}
Output
[Go supports tabs and newlines]
Choose strings.Split(text, " ") when every literal space matters. Choose strings.Fields(text) when any run of whitespace should act as one separator.
Split a Go String by Newline
To split text into lines, use the newline character "\n" as the separator.
package main
import (
"fmt"
"strings"
)
func main() {
text := "first line\nsecond line\nthird line"
lines := strings.Split(text, "\n")
for _, line := range lines {
fmt.Println(line)
}
}
Output
first line
second line
third line
Text created on systems that use "\r\n" line endings may leave a trailing carriage-return character when split only on "\n". When necessary, remove it with strings.TrimSuffix(line, "\r") or normalize the line endings before splitting.
Limit the Number of Parts with strings.SplitN()
strings.Split() separates the string at every occurrence of the delimiter. Use strings.SplitN() when only a limited number of returned parts is required.
strings.SplitN(str, separator, n)
For a positive n, the returned slice contains at most n elements. The final element contains the unsplit remainder.
package main
import (
"fmt"
"strings"
)
func main() {
record := "name:Arun:Administrator"
parts := strings.SplitN(record, ":", 2)
fmt.Printf("%q\n", parts)
}
Output
["name" "Arun:Administrator"]
This is useful for values such as key-value records where the value itself may contain the same delimiter.
Behavior When the Delimiter Is Missing or Empty
If the separator does not occur in the input, strings.Split() returns a one-element slice containing the original string.
package main
import (
"fmt"
"strings"
)
func main() {
parts := strings.Split("golang", ",")
fmt.Printf("%q\n", parts)
}
Output
["golang"]
If the separator is an empty string, Go splits the input after each UTF-8 sequence, producing string elements that correspond to the encoded characters.
package main
import (
"fmt"
"strings"
)
func main() {
characters := strings.Split("Go語", "")
fmt.Printf("%q\n", characters)
}
Output
["G" "o" "語"]
For direct Unicode character processing, converting the string to []rune is often clearer because it represents code points rather than string fragments.
Empty Elements at the Start, Middle, or End
strings.Split() preserves empty fields created by adjacent delimiters or delimiters at the boundaries of the input.
package main
import (
"fmt"
"strings"
)
func main() {
values := strings.Split(",a,,b,", ",")
fmt.Printf("%q\n", values)
}
Output
["" "a" "" "b" ""]
If empty values are not valid for your use case, filter them after splitting instead of assuming they will be removed automatically.
Split a String at the First Matching Delimiter
To separate a string into exactly two logical sections at the first delimiter, use strings.Cut(). It returns the text before the delimiter, the text after it, and a Boolean indicating whether the delimiter was found.
package main
import (
"fmt"
"strings"
)
func main() {
key, value, found := strings.Cut("language=Go", "=")
fmt.Println(key)
fmt.Println(value)
fmt.Println(found)
}
Output
language
Go
true
Use strings.Cut() when you only need the first match. Use strings.SplitN(value, separator, 2) when a slice result is more convenient.
Split a Go String at a Known Index
Splitting by index does not require strings.Split(). Slice the string into two sections when the index is a byte position.
package main
import "fmt"
func main() {
text := "golang"
index := 2
left := text[:index]
right := text[index:]
fmt.Println(left)
fmt.Println(right)
}
Output
go
lang
String indexes in Go are byte indexes. For text containing multibyte Unicode characters, convert the string to []rune before splitting by character position.
package main
import "fmt"
func main() {
characters := []rune("Go語言")
index := 2
left := string(characters[:index])
right := string(characters[index:])
fmt.Println(left)
fmt.Println(right)
}
Output
Go
語言
Choosing the Correct Go String-Splitting Function
| Requirement | Recommended approach |
|---|---|
| Split at every exact delimiter | strings.Split() |
| Return at most a fixed number of parts | strings.SplitN() |
| Split words across spaces, tabs, and newlines | strings.Fields() |
| Split once at the first delimiter | strings.Cut() |
| Split at a byte position | String slicing |
| Split at a Unicode character position | Convert to []rune, then slice |
Common Mistakes When Splitting Strings in Go
- Forgetting to import
strings: Functions such asSplit,SplitN, andFieldsbelong to the standard-librarystringspackage. - Expecting delimiters in the result:
strings.Split()removes the separator and returns only the parts around it. - Ignoring empty elements: Consecutive or boundary delimiters produce empty strings in the returned slice.
- Using a literal space for irregular whitespace: Prefer
strings.Fields()when the input can contain repeated spaces, tabs, or newlines. - Treating string indexes as character indexes: Go string indexes refer to bytes, which can split a multibyte UTF-8 character incorrectly.
Frequently Asked Questions About Splitting Strings in Go
How do I split a string in Go?
Import the strings package and call strings.Split(value, separator). The function returns a []string containing every part separated by the exact delimiter.
How do I split a Go string by spaces without empty elements?
Use strings.Fields(). It treats consecutive Unicode whitespace characters as a single boundary and omits empty fields.
How do I split a string only once in Go?
Use strings.Cut() to split around the first occurrence and receive separate before-and-after values. You can also use strings.SplitN(value, separator, 2) to obtain a two-element slice.
What happens when strings.Split() cannot find the separator?
It returns a one-element slice containing the complete original string.
How do I split a Go string into individual characters?
You can call strings.Split(value, ""). For Unicode-aware character processing, converting the value to []rune is generally clearer and lets you index or iterate by code point.
Go String Splitting Editorial QA Checklist
- Confirm every example imports the
stringspackage when it uses a strings function. - Verify that output blocks show empty elements clearly with quoted formatting where needed.
- Check whether the example requires an exact separator, flexible whitespace handling, or a limited number of parts.
- Confirm that byte indexes and Unicode character indexes are not presented as equivalent.
- Test edge cases involving missing delimiters, consecutive delimiters, and delimiters at the start or end.
Summary of Go String Splitting
In this Go Tutorial, we learned how to split a string in Go using strings.Split(). We also used strings.SplitN() for limited splitting, strings.Fields() for whitespace-separated words, strings.Cut() for the first delimiter, and slicing for splitting at a known index.
TutorialKart.com