GoLang String - Split()

In this tutorial, we will learn how to split a given string into slices using the Split() method along with working examples of it.

In the Go Language, Split() is used to break the given string into a slice. let us explore the uses case with help of simple examples.

String Split()

Split() is used to break the given string into a slice. It will split all the substrings by the separators (characters or symbols) and return the slice of substrings between those separators.

Syntax:

strings.Split(actual_string,"separator")

It takes two parameters.

Parameters:

actual_string is the string and separator is a character or special symbol that split the actual string into substrings.

It is important to specify the "strings" package in import.

Example 1:

Let us consider the string - "welcome to gkindex" and split it with space as separator - " "

CopiedCopy Code

package main

import (
    "fmt"
"strings")

func main() {
  
  // Consider the string
    var actual_string = "welcome to gkindex"
 
    fmt.Println("String: ", actual_string)

      // Split the string by space separator.
     fmt.Println(strings.Split(actual_string," "))
     
}

Output:

CopiedCopy Code

String:  welcome to gkindex
[welcome to gkindex]

Example 2:

Let us consider the string - "welcome to gkindex" and split it with space as separator - "m"

CopiedCopy Code

package main

import (
    "fmt"
"strings")

func main() {
  
  // Consider the string
    var actual_string = "welcome to gkindex"
 
    fmt.Println("String: ", actual_string)

      // Split the string by 'm' as separator.
     fmt.Println(strings.Split(actual_string,"m"))
     
}

Output:

CopiedCopy Code

String:  welcome to gkindex
[welco e to gkindex]

Explanation for the above output:

We can see that strings are splits with a separator-'m' and returned a slice of the substrings between the separator.

Example 3:

Let us consider the string - "welcome to gkindex" and

  1. Split it with space as separator - "a".
  2. Split it with space as separator - "b".
CopiedCopy Code

package main

import (
    "fmt"
"strings")

func main() {
  
  // Consider the string
    var actual_string = "aaabbbccaaabbcacab"
 
    fmt.Println("String: ", actual_string)

      // Split the string by 'a' as separator.
     fmt.Println(strings.Split(actual_string,"a"))
     
     // Split the string by 'b' as separator.
     fmt.Println(strings.Split(actual_string,"b"))
     
}

Output:

CopiedCopy Code

String:  aaabbbccaaabbcacab
[   bbbcc   bbc c b]
[aaa   ccaaa  caca ]

Conclusion

Now we know how to break the string into slice in a Golang using Split() function and understood the implementation with working examples.