ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

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
ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.