What is the split method in Scala?

Scala offers various functions for string manipulation, one of which is the split function. The split function can manipulate strings and split them into pieces at specified points.

Syntax

String[] split(String expression, int limit)

Parameters

The split function takes two parameters:

  • expression – specifies the character (or characters) to find and split at.

  • limit – is the number of pieces the string will be split into.

Return value

The function returns an array of strings. The function looks for the specified number of occurrences of the specified character to split. When the number is reached, the rest of the string is put at the last index of the array, regardless of whether it contains the specified character. Once the limit is reached, the function will not make any more splits.

Code

The following code shows the implementation of the split function.

// Example code for split() function
object Main extends App {
// splits at " " found in the string, stops at 4 pieces
val splitted = "This is an Edpresso shot".split(" ", 4)
for ( str <-splitted ) // iterate over array
{
println(str)
}
}

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved