<< Back to GO
Golang Split Examples (SplitAfter, SplitN)
Use Split from the strings package. Call SplitAfter and SplitN to separate strings.Split. Often strings are concatenated together, with many parts in a single string. They are separated by delimiter chars. We can split these into slices of many strings.
With the strings package, we gain access to the Split and Join methods. Split has many variants, and selecting one can be confusing. These methods are powerful.
To begin, we use the Split method—please note how we import the "strings" package at the top. Split returns a slice of strings. Split receives 2 arguments.
First argument: This is the data string we want to separate apart—it should contain a delimiter char or pattern.
Second argument: This is the delimiter char or string. The delimiter can be any length.
Golang program that uses strings, Split method
package main
import (
"fmt"
"strings"
)
func main() {
data := "cat,bird,dog"
// Split on comma.
result := strings.Split(data, ",")
// Display all elements.
for i := range result {
fmt.Println(result[i])
}
// Length is 3.
fmt.Println(len(result))
}
Output
cat
bird
dog
3
Read file lines. This example reads in a text file that has multiple lines. It then splits each line as we encounter it. The bufio package is used to provide a Scan() method.
Part 1: We open the file.txt text file on the local disk. Please adjust this file name to one that is valid on your system.
Part 2: We use a for-loop and call Scan() and Text() to get the current line. Inside the loop, we split each line on its commas.
Golang program that splits all lines in file
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
func main() {
// Part 1: open the file and scan it.
f, _ := os.Open("C:\\programs\\file.txt")
scanner := bufio.NewScanner(f)
// Part 2: call Scan in a for-loop.
for scanner.Scan() {
line := scanner.Text()
// Split the line on commas.
parts := strings.Split(line, ",")
// Loop over the parts from the string.
for i := range parts {
fmt.Println(parts[i])
}
// Write a newline.
fmt.Println()
}
}
Output
red
yellow
green
blue
square
circle
Contents of file.txt
red,yellow,green,blue
square,circle
SplitAfter. This method splits on a zero-character position that comes after the specified delimiter. All the delimiters are retained in the resulting substrings.
So: SplitAfter separates at the point directly after the delimiter you specify. This can be useful if you want to keep delimiters.
Golang program that uses SplitAfter
package main
import (
"fmt"
"strings"
)
func main() {
value := "one.two.three"
// Split after the period.
result := strings.SplitAfter(value, ".")
// Display our results.
for i := range(result) {
fmt.Println(result[i])
}
}
Output
one.
two.
three
Regexp Split. A regular expression can be used to split a string. We first compile a regexp with MustCompile. The regexp uses a pattern that matches delimiters in a string.
Regexp: MustCompile, SplitHere: We split on the characters X and Y. The string is split into a slice of three substrings.
Note: The second argument to regexp Split is the "limit" on the number of substrings to split. A negative number indicates no limit.
Golang program that uses regexp Split method
package main
import (
"fmt"
"regexp"
)
func main() {
value := "catXdogYbird"
// First compile the delimiter expression.
re := regexp.MustCompile(`[XY]`)
// Split based on pattern.
// ... Second argument means "no limit."
result := re.Split(value, -1)
for i := range(result) {
fmt.Println(result[i])
}
}
Output
cat
dog
bird
Individual chars. With SplitAfter, we can extract the individual characters of a string into a string slice. We split after an empty string.
Golang program that splits string into single chars
package main
import (
"fmt"
"strings"
)
func main() {
value := "bird"
// Split after an empty string to get all letters.
result := strings.SplitAfter(value, "")
for i := range(result) {
// Get letter and display it.
letter := result[i]
fmt.Println(letter)
}
}
Output
b
i
r
d
SplitN. This method receives an argument that indicates the max number of strings to return. So if you pass 3, only the first two delimiters will be split upon.
Total: The third argument to SplitN is the max number of strings in the resulting slice. The final string may have remaining delimiters.
Golang program that uses SplitN
package main
import (
"fmt"
"strings"
)
func main() {
value := "12|34|56|78"
// Split into three parts.
// ... The last separator is not split.
result := strings.SplitN(value, "|", 3)
for v := range(result) {
fmt.Println(result[v])
}
}
Output
12
34
56|78
Fields, FieldsFunc. Consider also the Fields() method. It treats a sequence of delimiter chars as a single delimiter (unlike Split). We can use it with spaces or another character.
Fields
Join. Take a string and split it apart. We can join it together again with join(), and this is often done in Go. We invoke strings.Join as part of the strings package.
Join
With Split, SplitN, SplitAfter and SplitAfterN we separate strings. These methods return a string slice—this is idiomatic Go. Join meanwhile combines strings.
Strings
Related Links:
- Golang strconv, Convert Int to String
- Golang Odd and Even Numbers
- Golang Recover Built In: Handle Errors, Panics
- Learn Go Language Tutorial
- Golang html template Example
- Golang http.Get Examples: Download Web Pages
- Golang container list Example (Linked List)
- Golang base64 Encoding Example: EncodeToString
- Golang os exec Examples: Command Start and Run
- Golang String Between, Before and After
- Golang os.Remove: Delete All Files in Directory
- Golang First Words in String
- Golang flag Examples
- Golang Regexp Find Examples: FindAllString
- Golang Regexp Examples: MatchString, MustCompile
- Golang Index, LastIndex: strings Funcs
- Golang Compress GZIP Examples
- Golang Interface Example
- Golang 2D Slices and Arrays
- Golang Sscan, Sscanf Examples (fmt)
- Top 41 Go Programming (Golang) Interview Questions (2021)
- Golang Padding String Example (Right or Left Align)
- Golang Equal String, EqualFold (If Strings Are the Same)
- Golang map Examples
- Golang Map With String Slice Values
- Golang Array Examples
- Golang Remove Duplicates From Slice
- Golang If, Else Statements
- Golang ParseInt Examples: Convert String to Int
- Golang Strings
- Golang strings.Map func
- Golang bufio.ScanBytes, NewScanner (Read Bytes in File)
- Golang Built In Functions
- Golang bytes.Buffer Examples (WriteString, Fprintf)
- Golang Bytes: Slices and Methods
- Golang Caesar Cipher Method
- Golang Chan: Channels, Make Examples
- Golang Math Module: math.Abs, Pow
- Golang Reverse String
- Golang Struct Examples: Types and Pointers
- Golang path and filepath Examples (Base, Dir)
- Golang Substring Examples (Rune Slices)
- Golang Suffixarray Examples: New, Lookup Benchmark
- Golang switch Examples
- Golang Convert Map to Slice
- Golang Convert Slice to String: int, string Slices
- Golang Const, Var Examples: Iota
- Golang ROT13 Method
- Golang strings.Contains and ContainsAny
- Golang rand, crypto: Random Number Generators
- Golang String Literal Examples (Repeat Method)
- Golang ToLower, ToUpper String Examples
- Golang Trim, TrimSpace and TrimFunc Examples
- Golang Join Examples (strings.Join)
- Golang Len (String Length)
- Golang Convert String to Rune Slice (append)
- Golang JSON Example: Marshal, Unmarshal
- Golang Replace String Examples: Replacer, NewReplacer
- Golang nil (Cannot Use nil as Type)
- Golang Slice Examples
- Golang ListenAndServe Examples (HandleFunc)
- Golang Fibonacci Sequence Example
- Golang Time: Now, Parse and Duration
- Golang bits, OnesCount (Get Bitcount From Int)
- Golang Fprint, Fprintf and Fprintln Examples (fmt)
- Golang Func Examples
- Golang csv Examples
- Golang Fields and FieldsFunc
- Golang unicode.IsSpace (If Char Is Whitespace)
- Golang fmt.Println Examples
- Golang for Loop Examples: Foreach and While
- Golang ioutil.WriteFile, os.Create (Write File to Disk)
- Golang File Handling
- Golang range: Slice, String and Map
- Golang Readdir Example (Get All Files in Directory)
- Golang Sort Slice: Len, Less, Swap in Interface
- Golang Get Lines in File (String Slice)
- Golang Split Examples (SplitAfter, SplitN)
Related Links
Adjectives
Ado
Ai
Android
Angular
Antonyms
Apache
Articles
Asp
Autocad
Automata
Aws
Azure
Basic
Binary
Bitcoin
Blockchain
C
Cassandra
Change
Coa
Computer
Control
Cpp
Create
Creating
C-Sharp
Cyber
Daa
Data
Dbms
Deletion
Devops
Difference
Discrete
Es6
Ethical
Examples
Features
Firebase
Flutter
Fs
Git
Go
Hbase
History
Hive
Hiveql
How
Html
Idioms
Insertion
Installing
Ios
Java
Joomla
Js
Kafka
Kali
Laravel
Logical
Machine
Matlab
Matrix
Mongodb
Mysql
One
Opencv
Oracle
Ordering
Os
Pandas
Php
Pig
Pl
Postgresql
Powershell
Prepositions
Program
Python
React
Ruby
Scala
Selecting
Selenium
Sentence
Seo
Sharepoint
Software
Spellings
Spotting
Spring
Sql
Sqlite
Sqoop
Svn
Swift
Synonyms
Talend
Testng
Types
Uml
Unity
Vbnet
Verbal
Webdriver
What
Wpf