- Published on
How to split string in golang?
Table of content
String Splitting in Golang
String splitting involves dividing a given string into multiple substrings based on a specific delimiter. In Golang, this operation is made seamless with the help of the built-in strings package. This package offers a variety of functions to split strings, each catering to different requirements.
Let's explore some of the most commonly used methods:
strings.Split
Function
Using the The strings.Split
function is your go-to tool for splitting strings in Golang.
It takes two arguments: input string and delimiter. The function then returns a slice of substrings obtained by splitting the original string at occurrences of the delimiter.
package main
import (
"fmt"
"strings"
)
func main() {
input := "apple,banana,grape,orange"
delimiter := ","
substrings := strings.Split(input, delimiter)
for _, s := range substrings {
fmt.Println(s)
}
}
strings.Fields
for Whitespace Separation
Splitting with Another handy function provided by the strings package is strings.Fields
. This function splits a string into substrings based on whitespace characters, such as spaces and tabs.
package main
import (
"fmt"
"strings"
)
func main() {
input := "Hello world, Golang"
substrings := strings.Fields(input)
for _, s := range substrings {
fmt.Println(s)
}
}
strings.SplitN
for Limited Splits
Splitting with In scenarios where you need to limit the number of splits, strings.SplitN comes to the rescue. This function takes an extra parameter specifying the maximum number of splits to perform.
package main
import (
"fmt"
"strings"
)
func main() {
input := "one, two, three, four, five"
delimiter := ","
limit := 3
substrings := strings.SplitN(input, delimiter, limit)
for _, s := range substrings {
fmt.Println(s)
}
}
Advanced String Splitting Techniques
Using Regular Expressions for Flexible Splitting
Golang empowers you to split strings using regular expressions through the regexp package. This provides unparalleled flexibility in defining custom splitting patterns.
package main
import (
"fmt"
"regexp"
)
func main() {
input := "apple+banana|grape=orange"
pattern := "[+|=]"
re := regexp.MustCompile(pattern)
substrings := re.Split(input, -1)
for _, s := range substrings {
fmt.Println(s)
}
}
Splitting and Filtering Empty Substrings
Sometimes, you may encounter situations where consecutive delimiters result in empty substrings. You can efficiently eliminate these empty substrings using the strings.Split function along with a filter.
package main
import (
"fmt"
"strings"
)
func main() {
input := "apple,,banana,,grape,,orange"
delimiter := ","
substrings := strings.FieldsFunc(input, func(r rune) bool {
return r == ',' // Filter out empty substrings
})
for _, s := range substrings {
fmt.Println(s)
}
}