How to split the string based on delimiter in Go Language?
Contents
Split function in Golang
The Split function is used to divide the input string into a slice of sub strings based on the separators. The split function is defined in the String package of Go language. We need to import the String package in our program for accessing the Split function.
Syntax for Split function
1 |
func Split(s, sep string) []string |
The first argument S is the Input string slices. The separator needs to specify in the second argument of Split function. The function split the string into a slice of sub string by the given separator and returns the values in an array.
Golang program to split the string based on delimiter
The input string contains the employee details such as Name,Designation,Location, Hire_Date and those values are separated by comma (,). Lets write the Golang program to split the values based on delimiter using Split function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
package main import ( "fmt" "strings" ) func main() { data := "Peter,Manager,London,2019-10-12" // Split the string based on delimiter "," result := strings.Split(data, ",") fmt.Println("\nInput : ", data) fmt.Println("\nResult : ", result) // print the length. fmt.Println("\nLength of String slice: ",len(result)) // Returns the array of strings. fmt.Println("\n ---- Name,Designation,Location,Hire_Date ----") for i := range result { fmt.Println(result[i]) } } |
The slice of sub string are stored in the result variable. Since the returned values are array of strings, the for loop is used to print each values as below.
Output
1 2 3 4 5 6 7 8 9 10 11 |
Input : Peter,Manager,London,2019-10-12 Result : [Peter Manager London 2019-10-12] Length of String slice: 4 ---- Name,Designation,Location,Hire_Date ---- Peter Manager London 2019-10-12 |
Recommended Articles