Scala program to split string

Scala | Split string example: Here, we are going to learn how to split strings in Scala programming language?
Submitted by Shivang Yadav, on April 21, 2020 [Last updated : March 10, 2023]

A string is a collection that stores multiple characters, it is an immutable sequence which cannot be changed.

Scala – Splitting a String

In Scala, using the split() method one can split the string in an array based on the required separator like commas, spaces, line-breaks, symbols or any regular expression.

Syntax

    string.split("saperator")

Scala code to split a string

object MyClass {
       def main(args: Array[String]) {
        val string = "Hello! Welcome to includeHelp..."
        println(string)
        
        val stringContents = string.split(" ")
        
        println("Content of the string are: ")
        for(i <- 0 to stringContents.length-1)
            println(stringContents(i))
    }
}

Output

Hello! Welcome to includeHelp...
Content of the string are: 
Hello!
Welcome
to
includeHelp...

This method is useful when we are working with data that are encoded in a string like URL-encoded string, multiline data from servers, etc where the string need to be split to extract information. One major type is when data comes in the form of CSV (comma-separated value) strings which is most common and needs each value to be separated from the string.

Let's see how to,

Scala code to split a CSV string using split method

object MyClass {
       def main(args: Array[String]) {
        val CSVstring = "ThunderBird350 , S1000RR, Iron883, StreetTripleRS"
        println(CSVstring)
        
        val stringContents = CSVstring.split(", ")
        
        println("Content of the string are: ")
        for(i <- 0 to stringContents.length-1)
            println(stringContents(i))
    }
}

Output

ThunderBird350 , S1000RR, Iron883, StreetTripleRS
Content of the string are: 
ThunderBird350 
S1000RR
Iron883
StreetTripleRS

Scala Code for Splitting String using Regular Expressions

In the split method, a regular expression(regex) can also be used as a separator to split strings.

object MyClass {
       def main(args: Array[String]) {
        val string = "1C 2C++ 3Java"
        println(string)
        
        val stringContents = string.split("\\d+")
        
        println("Content of the string are: ")
        
        for(i <- 0 to stringContents.length-1)
            println(stringContents(i))
    }
}

Output

1C 2C++ 3Java
Content of the string are: 

C 
C++ 
Java

Here, we have separated the string using the regex \\d+ which considers any digit. In our string, the function will split every time a digit is encountered.

Scala String Programs »



Related Programs



Comments and Discussions!

Load comments ↻





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