Q:

Scala program to split string

belongs to collection: Scala String Programs

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program to split a string in Scala

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,

Program 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

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Scala String Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Scala program to convert string to integer... >>
<< How to determine if a string contains a regular ex...