![]() |
VOOZH | about |
In Go language, strings differ from other languages like Java, C++, and Python. A string in Go is a sequence of variable-width characters, with each character represented by one or more bytes using UTF-8 encoding. In Go, you can split a string into a slice using several functions provided in the strings package. In this article,we will learn How to Split a String in Golang?
package main
import (
"fmt"
"strings"
)
func main() {
str := "Welcome,to,GeeksforGeeks"
fmt.Println("Original String:", str)
}
Here, the string "Welcome,to,GeeksforGeeks" will be split using different methods. First, ensure you have imported the strings package to access the split functions.
func Split(s, sep string) []string #UsingSplitFunction
func SplitAfter(s, sep string) []string # UsingSplitAfterFunction
func SplitN(s, sep string, n int) []string # UsingSplitNFunction
func SplitAfterN(s, sep string, n int) []string # UsingSplitAfterNFunction
Split FunctionThe Split function divides a string into all substrings separated by the specified separator and returns a slice with these substrings.
func Split(s, sep string) []string
s: The string to be split.sep: The separator. Ifsepis empty, it splits after each UTF-8 character. If bothstrandsepare empty, it returns an empty slice.
Example
Welcome,to,GeeksforGeeks Result: [Welcome to GeeksforGeeks]
SplitAfter FunctionThe SplitAfter function splits a string after each instance of the specified separator and returns a slice.
func SplitAfter(s, sep string) []stringNote:
- If
sepis empty, it splits after each UTF-8 sequence.- If
sdoesn’t containsep, it returns a slice of length 1 withs.
Example
Welcome,to,GeeksforGeeks Result: [Welcome, to, GeeksforGeeks]
SplitN FunctionThe SplitN function splits a string into a maximum number of substrings.
func SplitN(s, sep string, n int) []string
n > 0: Splits up tonsubstrings.n == 0: Returns an empty slice.n < 0: Returns all substrings.
Example:
Welcome,to,GeeksforGeeks Result: [Welcome to,GeeksforGeeks]
SplitAfterN FunctionThe SplitAfterN function splits a string after each instance of the separator, but only up to n substrings.
func SplitAfterN(str, sep string, n int) []string
- n > 0: Splits up to n substrings.
- n == 0: Returns an empty slice.
- n < 0: Returns all substrings.
Example:
Welcome,to,GeeksforGeeks Result using SplitAfterN: [Welcome, to,GeeksforGeeks]
Each of these functions provides a flexible way to split strings in Go, depending on the use case and the desired output structure. By understanding these functions, you can more effectively handle string manipulation in your Go programs.