Golang | Splitting the string after the specified separator
In Go language, strings are different from other languages like Java, C++, Python, etc. It is a sequence of variable-width characters where each and every character is represented by one or more bytes using UTF-8 Encoding.
In the Go strings, you are allowed to split the string after the specified separator using a SplitN() function. This function splits a slice into all substrings after each instance of the given separator and returns a slice of the substrings between those separators. The count indicates the number of subslices to return. It is defined under the string package so, you have to import string package in your program for accessing SplitN function.
Syntax:
func SplitN(str, sep string, m int) []string
Here, str is the string and sep is the separator. If str does not contain the given sep and sep is non-empty, then it will return a slice of length 1 which contain only str. Or if the sep is empty, then it will split after each UTF-8 sequence. Or if both str and sep are empty, then it will return an empty slice.
Example 1:
package main
import (
"fmt"
"strings"
)
func main() {
res1 := strings.SplitN( "****Welcome, to, GeeksforGeeks****" , "," , -1)
res2 := strings.SplitN( "Learning x how x to x trim" +
" x a x slice of bytes" , "x" , 3)
res3 := strings.SplitN( "Geeks,for,Geeks, Geek" , "," , 0)
res4 := strings.SplitN( "" , "," , 2)
fmt.Printf( "\nFinal Result after splitting:\n" )
fmt.Printf( "\nSlice 1: %s" , res1)
fmt.Printf( "\nSlice 2: %s" , res2)
fmt.Printf( "\nSlice 3: %s" , res3)
fmt.Printf( "\nSlice 4: %s" , res4)
}
|
Output:
Final Result after splitting:
Slice 1: [****Welcome to GeeksforGeeks****]
Slice 2: [Learning how to x trim x a x slice of bytes]
Slice 3: []
Slice 4: []
Example 2:
package main
import (
"fmt"
"strings"
)
func main() {
string_1 := "Welcome, to, Geeks, for, Geeks"
string_2 := "AppleAppleAppleAppleAppleApple"
string_3 := "%G%E%E%K%sS"
fmt.Println( "Original Strings:" )
fmt.Printf( "String 1: %s" , string_1)
fmt.Printf( "\nString 2: %s" , string_2)
fmt.Printf( "\nString 3: %s" , string_3)
res1 := strings.SplitN(string_1, "," , 2)
res2 := strings.SplitN(string_2, "pp" , 3)
res3 := strings.SplitN(string_3, "%" , 0)
fmt.Printf( "\n\nAfter splitting:\n" )
fmt.Printf( "\nString 1: %s" , res1)
fmt.Printf( "\nString 2: %s" , res2)
fmt.Printf( "\nString 3: %s" , res3)
}
|
Output:
Original Strings:
String 1: Welcome, to, Geeks, for, Geeks
String 2: AppleAppleAppleAppleAppleApple
String 3: %G%E%E%K%sS
After splitting:
String 1: [Welcome to, Geeks, for, Geeks]
String 2: [A leA leAppleAppleAppleApple]
String 3: []
Last Updated :
05 Sep, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...