Scala String split() Method with Example

Here, we will learn about the split() method in Scala. The split() method is used to split string to array of string. We will see its working, syntax and examples.
Submitted by Shivang Yadav, on January 30, 2021

String is an immutable collection that stores sequences of characters.

String split() Method

The split() method in Scala is used to split the given string into an array of strings using the separator passed as parameter. You can alternatively limit the total number of elements of the array using limit.

Syntax:

string_Name.split(separator, limit(optional))

Parameters: The method accepts two parameters one of which is optional,

  1. separator which is a substring used to split the given string.
  2. limit which is an integer value that limits the total number of elements in the resultant array.

Return Value: It returns an array of strings consisting of all splitted strings.

Example 1:

object MyClass {
    def main(args: Array[String]) {
        val myString = "abaababbccsabaaba"
        println("The string is '" + myString + "'")
        
        val splitArray = myString.split("s")

        println("Printing the array of strings : ")
        for(i <- splitArray)
            println(i)
    }
}

Output:

The string is 'abaababbccsabaaba'
Printing the array of strings : 
abaababbcc
abaaba

Example 2:

object MyClass {
    def main(args: Array[String]) {
        val myString = "abaababccsabaaba"
        println("The string is '" + myString + "'")
        
        val splitArray = myString.split("b")
    
        println("Printing the array of strings : ")
        for(i <- splitArray)
            println(i)
    }
}

Output:

The string is 'abaababccsabaaba'
Printing the array of strings : 
a
aa
a
ccsa
aa
a

Example 3: Split method with limit parameter

object MyClass {
    def main(args: Array[String]) {
        val myString = "abaababccsabaaba"
        println("The string is '" + myString + "'")
        
        val splitArray = myString.split("b", 4)
    
        println("Printing the array of strings : ")
        for(i <- splitArray)
            println(i)
    }
}

Output:

The string is 'abaababccsabaaba'
Printing the array of strings : 
a
aa
a
ccsabaaba


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.