Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   






Split() FUNCTION


Split() Function


The Split() Function is used to split a string based on the value provided.


Example :



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)  
    } 
}


Output :



 arr[ 0 ] = Hello
 arr[ 1 ] = Beautiful
 arr[ 2 ] = World

So, in the above code, we have a String 'Hello Beautiful World' initialised to a variable 'x'.


java_Collections

Then we have used the 'split()' function on the variable 'x'.


var arr []string = strings.Split(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'.


java_Collections

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 '@'.


"Hello@Beautiful@World"

Now, if you want to form an array with 'Hello', 'Beautiful' and 'World'. You can use 'Split()' function providing the separator '@' as argument.


'Split()' Function using separator as an argument


Example :



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)  
    } 
}


Output :



 arr[ 0 ] = Hello
 arr[ 1 ] = Beautiful
 arr[ 2 ] = World

So, in the above code, we have a String 'Hello@Beautiful@World' initialised to a variable 'x'.


java_Collections

Then we have used the 'split()' function with the separator '@' as argument on the variable 'x'.


var arr []string = strings.Split(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'.


java_Collections