Use the strings.Split function from the standard library to break a string into a slice of substrings based on a specific delimiter. If you need to limit the number of splits, use strings.SplitN instead, which returns the remaining string as the final element if the count is exceeded.
Here is a basic example splitting a CSV line into fields:
package main
import (
"fmt"
"strings"
)
func main() {
csvLine := "apple,banana,cherry,date"
fields := strings.Split(csvLine, ",")
fmt.Println(fields) // Output: [apple banana cherry date]
fmt.Println(fields[1]) // Output: banana
}
If your delimiter might appear multiple times and you only want the first few parts, strings.SplitN is more efficient. For instance, splitting a "key:value" pair where the value itself might contain colons:
package main
import (
"fmt"
"strings"
)
func main() {
input := "user:admin:192.168.1.1"
// Split into max 2 parts: key and the rest of the value
parts := strings.SplitN(input, ":", 2)
if len(parts) == 2 {
fmt.Println("Key:", parts[0]) // Output: Key: user
fmt.Println("Value:", parts[1]) // Output: Value: admin:192.168.1.1
}
}
Be aware that strings.Split returns an empty slice if the input string is empty, but returns a slice containing one empty string if the input is just the delimiter (e.g., strings.Split(",", ",") returns ["", ""]). If you are processing user input or log files, always check the length of the resulting slice before accessing indices to avoid panics. For large strings or performance-critical paths, consider using strings.SplitN with a count of 1 to check for existence without allocating the full slice, or use strings.Index if you only need to locate the delimiter.