TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< 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, Split

Here: 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
© TheDeveloperBlog.com
The Dev Codes

Related Links:


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