Splitting a Slice Separated by the Specified Expression in Golang


In Golang, slices are used to store sequences of elements of the same type. Slicing a slice is a common operation in Golang, but sometimes we need to split a slice based on a specified separator. Golang provides a built-in function to split a string based on a separator, but splitting a slice is a bit different. In this article, we will explore how to split a slice separated by the specified expression in Golang.

Using the Strings Package

The strings package in Golang provides the Split() function, which is used to split a string into a slice based on a separator. We can use the same function to split a slice by converting it into a string.

Example

package main

import (
   "fmt"
   "strings"
)

func main() {
   s := []string{"hello-world", "golang-is-great", "slice-is-fun"}
   sep := "-"

   for _, v := range s {
      result := strings.Split(v, sep)
      fmt.Println(result)
   }
}

Output

[hello world]
[golang is great]
[slice is fun]

In the above example, we have a slice s which contains three strings separated by -. We have defined the separator as - in the sep variable. We then loop through each element of the slice and split it using the Split() function of the strings package. The resulting slice is printed using the fmt package.

Using a Custom Function

We can also create our own custom function to split a slice based on a separator. In this approach, we loop through each element of the slice and split it based on the separator. We then add the resulting slice to a new slice.

Example

package main

import (
   "fmt"
   "strings"
)

func splitSlice(s []string, sep string) [][]string {
   result := [][]string{}

   for _, v := range s {
      temp := strings.Split(v, sep)
      result = append(result, temp)
   }
   return result
}

func main() {
   s := []string{"hello-world", "golang-is-great", "slice-is-fun"}
   sep := "-"
   result := splitSlice(s, sep)
   fmt.Println(result)
}

Output

[[hello world] [golang is great] [slice is fun]]

In the above example, we have created a custom function splitSlice() that takes a slice and separator as input and returns a slice of slices. We loop through each element of the input slice and split it based on the separator. We then add the resulting slice to a new slice result. The final result is returned by the function.

Conclusion

Splitting a slice by the specified expression is a common operation in Golang. We can use the built-in Split() function of the strings package or create a custom function to split the slice. The choice of method depends on the use case and personal preference.

Updated on: 19-Apr-2023

71 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements