Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Splitting the slice after the specified separator in Golang
In Golang, there are multiple ways to split a slice after a specified separator. This can be achieved using built-in functions and methods. In this article, we will explore some of the common ways to split a slice in Golang.
Using strings.SplitAfter Function
The strings package in Golang provides a SplitAfter function, which splits a string or slice of bytes after the specified separator and returns the result as a slice of strings
Example
package main
import (
"fmt"
"strings"
)
func main() {
slice := []string{"apple_", "banana_", "cherry_", "date_"}
sep := "_"
result := make([]string, 0)
for _, s := range slice {
result = append(result, strings.SplitAfter(s, sep)...)
}
fmt.Println(result)
}
Output
[apple_ banana_ cherry_ date_ ]
Using bytes.SplitAfter Function
The bytes package in Golang provides a SplitAfter function, which splits a slice of bytes after the specified separator and returns the result as a slice of slices of bytes.
Example
package main
import (
"bytes"
"fmt"
)
func main() {
slice := [][]byte{{97, 112, 112, 108, 101, 95}, {98, 97, 110, 97, 110, 97, 95}, {99, 104, 101, 114, 114, 121, 95}, {100, 97, 116, 101, 95}}
sep := []byte{'_'}
result := make([][]byte, 0)
for _, s := range slice {
result = append(result, bytes.SplitAfter(s, sep)...)
}
fmt.Println(result)
}
Output
[[97 112 112 108 101 95] [] [98 97 110 97 110 97 95] [] [99 104 101 114 114 121 95] [] [100 97 116 101 95] []]
Using Custom Function
We can also write a custom function to split a slice after a specified separator.
Example
package main
import (
"fmt"
"strings"
)
func splitAfter(slice []string, sep string) []string {
result := make([]string, 0)
for _, s := range slice {
index := 0
for {
i := strings.Index(s[index:], sep)
if i == -1 {
break
}
result = append(result, s[index:i+index+len(sep)])
index = i + index + len(sep)
}
result = append(result, s[index:])
}
return result
}
func main() {
slice := []string{"apple_", "banana_", "cherry_", "date_"}
sep := "_"
result := splitAfter(slice, sep)
fmt.Println(result)
}
Output
[apple_ banana_ cherry_ date_]
Conclusion
In this article, we explored some of the common ways to split a slice after a specified separator in Golang. We used the built-in functions provided by the strings and bytes packages, as well as a custom function. Depending on the requirements and the type of slice, we can choose the appropriate method to split a slice in Golang.