The Wayback Machine - https://web.archive.org/web/20240829143053/https://www.geeksforgeeks.org/how-to-split-a-string-in-golang/
Open In App

How to Split a String in Golang?

Last Updated : 29 Feb, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In Go language, strings are different from other languages like Java, C++, Python, etc. It is a sequence of variable-width characters where each and every character is represented by one or more bytes using UTF-8 Encoding. In Go strings, you are allowed to split a string into a slice with the help of the following functions. These functions are defined under the strings package so, you have to import strings package in your program for accessing these functions:
1. Split: This function splits a string into all substrings separated by the given separator and returns a slice that contains these substrings.
Syntax: 

func Split(str, sep string) []string

Here, str is the string and sep is the separator. If str does not contain the given sep and sep is non-empty, then it will return a slice of length 1 which contains only str. Or if the sep is empty, then it will split after each UTF-8 sequence. Or if both str and sep are empty, then it will return an empty slice. 
Example:

Go




// Go program to illustrate how to split a string
package main
 
import (
    "fmt"
    "strings"
)
 
// Main function
func main() {
 
    // Creating and initializing the strings
    str1 := "Welcome, to the, online portal, of GeeksforGeeks"
    str2 := "My dog name is Dollar"
    str3 := "I like to play Ludo"
 
    // Displaying strings
    fmt.Println("String 1: ", str1)
    fmt.Println("String 2: ", str2)
    fmt.Println("String 3: ", str3)
 
    // Splitting the given strings
    // Using Split() function
    res1 := strings.Split(str1, ",")
    res2 := strings.Split(str2, "")
    res3 := strings.Split(str3, "!")
    res4 := strings.Split("", "GeeksforGeeks, geeks")
 
    // Displaying the result
 
    fmt.Println("\nResult 1: ", res1)
    fmt.Println("Result 2: ", res2)
    fmt.Println("Result 3: ", res3)
    fmt.Println("Result 4: ", res4)
 
}


Output:

String 1:  Welcome, to the, online portal, of GeeksforGeeks
String 2: My dog name is Dollar
String 3: I like to play Ludo

Result 1: [Welcome to the online portal of GeeksforGeeks]
Result 2: [M y d o g n a m e i s D o l l a r]
Result 3: [I like to play Ludo]
Result 4: []

2. SplitAfter: This function splits a string into all substrings after each instance of the given separator and returns a slice that contains these substrings.
Syntax: 

func SplitAfter(str, sep string) []string

Here, str is the string and sep is the separator. If str does not contain the given sep and sep is non-empty, then it will return a slice of length 1 which contains only str. Or if the sep is empty, then it will split after each UTF-8 sequence. Or if both str and sep are empty, then it will return an empty slice. 
Example:

Go




// Go program to illustrate how to split a string
package main
 
import (
    "fmt"
    "strings"
)
 
// Main function
func main() {
 
    // Creating and initializing the strings
    str1 := "Welcome, to the, online portal, of GeeksforGeeks"
    str2 := "My dog name is Dollar"
    str3 := "I like to play Ludo"
 
    // Displaying strings
    fmt.Println("String 1: ", str1)
    fmt.Println("String 2: ", str2)
    fmt.Println("String 3: ", str3)
 
    // Splitting the given strings
    // Using SplitAfter() function
    res1 := strings.SplitAfter(str1, ",")
    res2 := strings.SplitAfter(str2, "")
    res3 := strings.SplitAfter(str3, "!")
    res4 := strings.SplitAfter("", "GeeksforGeeks, geeks")
 
    // Displaying the result
    fmt.Println("\nResult 1: ", res1)
    fmt.Println("Result 2: ", res2)
    fmt.Println("Result 3: ", res3)
    fmt.Println("Result 4: ", res4)
 
}


Output:

String 1:  Welcome, to the, online portal, of GeeksforGeeks
String 2: My dog name is Dollar
String 3: I like to play Ludo

Result 1: [Welcome, to the, online portal, of GeeksforGeeks]
Result 2: [M y d o g n a m e i s D o l l a r]
Result 3: [I like to play Ludo]
Result 4: []

3. SplitAfterN: This function splits a string into all substrings after each instance of the given separator and returns a slice that contains these substrings.
Syntax: 

func SplitAfterN(str, sep string, m int) []string

Here, str is the string, sep is the separator, and m is used to find the number of substrings to return. Here, if m>0, then it returns at most m substrings and the last string substring will not split. If m == 0, then it will return nil. If m<0, then it will return all substrings.
Example:

Go




// Go program to illustrate how to split a string
package main
 
import (
    "fmt"
    "strings"
)
 
// Main function
func main() {
 
    // Creating and initializing the strings
    str1 := "Welcome, to the, online portal, of GeeksforGeeks"
    str2 := "My dog name is Dollar"
    str3 := "I like to play Ludo"
 
    // Displaying strings
    fmt.Println("String 1: ", str1)
    fmt.Println("String 2: ", str2)
    fmt.Println("String 3: ", str3)
 
    // Splitting the given strings
    // Using SplitAfterN() function
    res1 := strings.SplitAfterN(str1, ",", 2)
    res2 := strings.SplitAfterN(str2, "", 4)
    res3 := strings.SplitAfterN(str3, "!", 1)
    res4 := strings.SplitAfterN("", "GeeksforGeeks, geeks", 3)
 
    // Displaying the result
    fmt.Println("\nResult 1: ", res1)
    fmt.Println("Result 2: ", res2)
    fmt.Println("Result 3: ", res3)
    fmt.Println("Result 4: ", res4)
 
}


Output:

String 1:  Welcome, to the, online portal, of GeeksforGeeks
String 2: My dog name is Dollar
String 3: I like to play Ludo

Result 1: [Welcome, to the, online portal, of GeeksforGeeks]
Result 2: [M y dog name is Dollar]
Result 3: [I like to play Ludo]
Result 4: []


Previous Article
Next Article

Similar Reads

How to split a slice of bytes in Golang?
In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. In the Go slice of bytes, you are allowed to split the given slice using a Split()
3 min read
How to split a slice of bytes after the given separator in Golang?
In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. In the Go slice of bytes, you are allowed to split the slice after the specified s
3 min read
How to Split Text Using Regex in Golang?
What is regex? Is Regex the famous anime character? Oops, if you think so, you're likely to be disappointed. The Go programming language uses the term regexp to denote Regular expressions. Regular expressions are very important in the field of string processing. The "regexp" package in Go holds all necessary pre-built functions that implement regul
7 min read
Converting a string variable into Boolean, Integer or Float type in Golang
Various types of string conversions are needed while performing tasks in Golang. Package strconv is imported to perform conversions to and from string. String to Boolean Conversion ParseBool is used to convert string to boolean value. It accepts 1, t, T, TRUE, true, True as true and 0, f, F, FALSE, false, False as false. Any other value returns an
3 min read
How to Trim a String in Golang?
In Go language, strings are different from other languages like Java, C++, Python, etc. It is a sequence of variable-width characters where each and every character is represented by one or more bytes using UTF-8 Encoding. You can trim a string in different ways using the following list of functions. All these functions are defined under strings pa
6 min read
How to convert a string in uppercase in Golang?
In Go language, strings are different from other languages like Java, C++, Python, etc. It is a sequence of variable-width characters where each and every character is represented by one or more bytes using UTF-8 Encoding. In Go string, you are allowed to convert a string in the uppercase using the following functions. All these functions are defin
3 min read
How to convert a string in lower case in Golang?
In Go language, strings are different from other languages like Java, C++, Python, etc. It is a sequence of variable-width characters where each and every character is represented by one or more bytes using UTF-8 Encoding. In Go string, you are allowed to convert a string in the lowercase using ToLower() function. This function returns a copy of th
2 min read
Check if the given characters is present in Golang String
In Go language, strings are different from other languages like Java, C++, Python, etc. It is a sequence of variable-width characters where each and every character is represented by one or more bytes using UTF-8 Encoding. In Go strings, you are allowed to check the given characters present in the string using the given functions. These functions a
3 min read
How to Replace Characters in Golang String?
In Go language, strings are different from other languages like Java, C++, Python, etc. It is a sequence of variable-width characters where each and every character is represented by one or more bytes using UTF-8 Encoding. In Go strings, you are allowed to replace characters in the given string using the given functions. These functions are defined
4 min read
Repeating a String for Specific Number of Times in Golang
In Go language, strings are different from other languages like Java, C++, Python, etc. It is a sequence of variable-width characters where each and every character is represented by one or more bytes using UTF-8 Encoding. You are allowed to repeat a string of for a specific number of times with the help of the Repeat() Function. This method return
3 min read
How to find the index value of specified string in Golang?
In Go language, strings are different from other languages like Java, C++, Python, etc. It is a sequence of variable-width characters where each and every character is represented by one or more bytes using UTF-8 Encoding. In Go strings, you can find the first index value of the specified string from the original string using the following function
4 min read
How to find the last index value of specified string in Golang?
In Go language, strings are different from other languages like Java, C++, Python, etc. It is a sequence of variable-width characters where each and every character is represented by one or more bytes using UTF-8 Encoding. In Go strings, you can find the last index value of the specified string from the original string using the following functions
4 min read
How to Count the Number of Repeated Characters in a Golang String?
In Go language, strings are different from other languages like Java, C++, Python, etc. It is a sequence of variable-width characters where each and every character is represented by one or more bytes using UTF-8 Encoding. In Go string, you can count some specific Unicode code points or the number of non-overlapping instances of costr (Repeated Cha
2 min read
Check if the String starts with specified prefix in Golang
In Go language, strings are different from other languages like Java, C++, Python, etc. It is a sequence of variable-width characters where each and every character is represented by one or more bytes using UTF-8 Encoding. In Golang strings, you can check whether the string begins with the specified prefix or not with the help of HasPrefix() functi
2 min read
Check if the String ends with specified suffix in Golang
In Go language, strings are different from other languages like Java, C++, Python, etc. It is a sequence of variable-width characters where each and every character is represented by one or more bytes using UTF-8 Encoding. In Go strings, you can check whether the string ends with the specified suffix or not with the help of HasSuffix() function. Th
2 min read
How to check String for equality under Unicode case folding in Golang?
In Go language, strings are different from other languages like Java, C++, Python, etc. It is a sequence of variable-width characters where each and every character is represented by one or more bytes using UTF-8 Encoding. In Go strings, you are allowed to compare two strings with each other without any error even if they are written in different c
3 min read
Golang | How to find the index of rune in the string?
In Go language, strings are different from other languages like Java, C++, Python, etc. It is a sequence of variable-width characters where each and every character is represented by one or more bytes using UTF-8 Encoding. In the Go strings, you can also find the first index of the specified rune in the given string using IndexRune() function. This
3 min read
How to check the specified rune in Golang String?
In Go language, strings are different from other languages like Java, C++, Python, etc. It is a sequence of variable-width characters where each and every character is represented by one or more bytes using UTF-8 Encoding. In the Go strings, you are allowed to check the given string contain the specified rune in it using ContainsRune() function. Th
3 min read
Searching an element of string type in Golang slice
In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. In the Go slice, you can search an element of string type in the given slice of st
3 min read
Golang | Checking the string for the specified regular expression
A regular expression is a sequence of characters which define a search pattern. Go language support regular expressions. A regular expression is used for parsing, filtering, validating, and extracting meaningful information from large text, like logs, the output generated from other programs, etc. In Go regexp, you are allowed to check whether the
3 min read
Golang | Splitting the string after the specified separator
In Go language, strings are different from other languages like Java, C++, Python, etc. It is a sequence of variable-width characters where each and every character is represented by one or more bytes using UTF-8 Encoding. In the Go strings, you are allowed to split the string after the specified separator using a SplitN() function. This function s
3 min read
Golang | Creating a string that contains regexp metacharacters
A regular expression is a sequence of characters which define a search pattern. Go language support regular expressions. A regular expression is used for parsing, filtering, validating, and extracting meaningful information from large text, like logs, the output generated from other programs, etc. In Go regexp, you are allowed to create a string th
2 min read
Golang | Extracting a Regular Expression from the String
A regular expression is a sequence of characters which define a search pattern. Go language support regular expressions. A regular expression is used for parsing, filtering, validating, and extracting meaningful information from large text, like logs, the output generated from other programs, etc. In Go regexp, you are allowed to extract a regular
2 min read
Golang | Extracting all the Regular Expression from the String
A regular expression is a sequence of characters which define a search pattern. Go language support regular expressions. A regular expression is used for parsing, filtering, validating, and extracting meaningful information from large text, like logs, the output generated from other programs, etc. In Go regexp, you are allowed to find all the regul
2 min read
Golang | Finding Index of the Regular Expression present in String
A regular expression is a sequence of characters which define a search pattern. Go language support regular expressions. A regular expression is used for parsing, filtering, validating, and extracting meaningful information from large text, like logs, the output generated from other programs, etc. In Go regexp, you are allowed to find the leftmost
2 min read
Golang | Replacing all String which Matches with Regular Expression
A regular expression is a sequence of characters which define a search pattern. Go language support regular expressions. A regular expression is used for parsing, filtering, validating, and extracting meaningful information from large text, like logs, the output generated from other programs, etc. In Go regexp, you are allowed to replace original s
2 min read
time.String() Function in Golang With Examples
In Go language, time packages supplies functionality for determining as well as viewing time. The String() function in Go language is used to find a string that represents the duration formats as "24h6m0.7s". Here, the foremost zero units are deleted. And the stated duration with less than one-second format will use a smaller unit, for example, mil
2 min read
time.Month.String() Function in Golang With Examples
In Go language, time packages supplies functionality for determining as well as viewing time. The Month.String() function in Go language is used to find the English name of the month. Moreover, this function is defined under the time package. Here, you need to import the "time" package in order to use these functions. Syntax: func (m Month) String(
2 min read
time.Weekday.String() Function in Golang With Examples
In Go language, time packages supplies functionality for determining as well as viewing time. The Weekday.String() function in Go language is used to find the English name of the day. Moreover, this function is defined under the time package. Here, you need to import the "time" package in order to use these functions. Syntax: func (d Weekday) Strin
1 min read
time.Location.String() Function in Golang With Examples
In Go language, time packages supplies functionality for determining as well as viewing time. The Location.String() function in Go language is used to find an explanatory name stated for the data of time zone which is equivalent to the name parameter passes to the LoadLocation or FixedZone method. Moreover, this function is defined under the time p
2 min read