×

Scala Tutorial

Scala Basics

Scala Control statements

Scala Functions

Scala Arrays

Scala Lists

Scala Strings

Scala Classes & Objects

Scala Collections

Scala String split() Method

By IncludeHelp Last updated : October 22, 2024

Description and Usage

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.