strings.Split() / Join() / Replace()
The Go strings package provides functions for splitting, joining, and replacing strings. These are fundamental text-processing operations used for tasks like parsing CSV data or formatting strings.
Syntax
import "strings" // Splits a string by the separator. parts := strings.Split(s, sep) // Splits into at most n substrings (n=-1 means no limit). parts := strings.SplitN(s, sep, n) // Joins a slice of strings with the separator. joined := strings.Join(parts, sep) // Replaces the first n occurrences of old with new (n=-1 replaces all). result := strings.Replace(s, old, new, n) // Replaces all occurrences (equivalent to strings.Replace(s, old, new, -1)). result := strings.ReplaceAll(s, old, new)
Function List
| Function | Description |
|---|---|
| strings.Split(s, sep) | Returns a slice of substrings by splitting s at each occurrence of sep. |
| strings.SplitN(s, sep, n) | Splits into at most n substrings. n=-1 means no limit. |
| strings.SplitAfter(s, sep) | Splits after each occurrence of sep, keeping the separator in each element. |
| strings.Fields(s) | Splits on runs of whitespace. Empty strings in the result are ignored. |
| strings.Join(elems, sep) | Returns a single string by joining the elements of a slice with sep. |
| strings.Replace(s, old, new, n) | Replaces up to n occurrences of old with new in s. Use n=-1 to replace all. |
| strings.ReplaceAll(s, old, new) | Replaces all occurrences of old with new in s. |
| strings.Map(f, s) | Applies function f to each rune in s and returns the transformed string. |
Sample Code
package main
import (
"fmt"
"strings"
)
func main() {
// Split: splits a string by a delimiter.
csv := "Alice,Bob,Charlie,Dave"
names := strings.Split(csv, ",")
fmt.Println("Split:", names)
fmt.Printf("Count: %d\n", len(names))
// SplitN: splits into at most N substrings.
parts := strings.SplitN(csv, ",", 2) // split into at most 2 parts
fmt.Println("SplitN(2):", parts) // ["Alice" "Bob,Charlie,Dave"]
fmt.Println()
// Fields: splits on whitespace.
text := " Go Language Programming "
words := strings.Fields(text) // leading, trailing, and consecutive spaces are ignored.
fmt.Println("Fields:", words)
fmt.Printf("Word count: %d\n", len(words))
fmt.Println()
// Join: joins a slice into a single string.
langs := []string{"Go", "Python", "Rust"}
joined := strings.Join(langs, " / ")
fmt.Println("Join:", joined)
fmt.Println()
// Replace: replaces substrings.
s := "apple apple apple"
fmt.Println("Replace(1):", strings.Replace(s, "apple", "orange", 1))
fmt.Println("Replace(-1):", strings.Replace(s, "apple", "orange", -1))
fmt.Println("ReplaceAll:", strings.ReplaceAll(s, "apple", "banana"))
fmt.Println()
// Practical example: simple CSV parsing.
csvLine := "1,John Doe,New York,30"
fields := strings.Split(csvLine, ",")
fmt.Printf("ID=%s Name=%s City=%s Age=%s\n", fields[0], fields[1], fields[2], fields[3])
// Path construction (efficiently joined with strings.Builder).
pathParts := []string{"home", "user", "documents", "file.txt"}
path := "/" + strings.Join(pathParts, "/")
fmt.Println("Path:", path)
}
Notes
strings.Split() splits a string by a delimiter, and strings.Join() does the reverse. This pair is a fundamental pattern in text processing. When you need to perform multiple replacements efficiently, strings.NewReplacer() is a faster alternative.
Calling strings.Split(s, "") splits the string byte by byte. To split a UTF-8 string (such as Japanese text) into individual characters, use a for-range loop over runes or convert the string to []rune(s).
For searching strings, see strings.Contains(). For case conversion and trimming, see strings.ToUpper() / ToLower() / TrimSpace().
If you find any errors or copyright issues, please contact us.