The Split() Function is used to split a string based on the value provided.
package main
import "fmt"
import "strings"
func main() {
x := "Hello Beautiful World"
var arr []string = strings.Split(x, " ")
for i, v := range arr {
fmt.Println("arr[",i,"] =", v)
}
}
So, in the above code, we have a String 'Hello Beautiful World' initialised to a variable 'x'.
-Function1.png)
Then we have used the 'split()' function on the variable 'x'.
So, the 'Split()' function converts the String, 'Hello Beautiful World' to an Array, separated by a space (i.e. ' ').
And initialises the array to the variable 'arr'.
-Function2.png)
So, if you see the above String, 'Hello Beautiful World'. 'Hello', 'Beautiful' and 'World' are separated by a space (i.e. ' ').
So, an array is formed with 'Hello', 'Beautiful' and 'World'.
But what if the Strings are separated by '@' or any other symbol.
Say, the below String is separated by '@'.
Now, if you want to form an array with 'Hello', 'Beautiful' and 'World'. You can use 'Split()' function providing the separator '@' as argument.
import "fmt"
import "strings"
func main() {
x := "Hello@Beautiful@World"
var arr []string = strings.Split(x, "@")
for i, v := range arr {
fmt.Println("arr[",i,"] =", v)
}
}
So, in the above code, we have a String 'Hello@Beautiful@World' initialised to a variable 'x'.
-Function3.png)
Then we have used the 'split()' function with the separator '@' as argument on the variable 'x'.
So, the 'Split()' function converts the String, 'Hello@Beautiful@World' to an Array, separated by the separator (i.e. '@').
And initialises the Array to the variable 'arr'.
-Function4.png)