How to use `splitAt` In Scala
The `splitAt` method offers a straightforward way to split an array into two sub-arrays at a specified index. It takes an integer index as input and returns a tuple containing two arrays:
- The first element in the tuple represents the sub-array containing elements from the original array up to, but not including, the provided index.
- The second element represents the sub-array containing elements from the specified index (inclusive) to the end of the original array.
Example:
object Main {
def main(args: Array[String]) {
val numbers = Array(1, 2, 3, 4, 5)
val (firstHalf, secondHalf) = numbers.splitAt(2) // Split at index 2
println(firstHalf.mkString(", ")) // Output: 1, 2
println(secondHalf.mkString(", ")) // Output: 3, 4, 5
}
}
How to split Array in Scala?
Arrays are a fundamental data structure in Scala, used to store collections of elements of the same type. Splitting an array involves dividing it into smaller sub-arrays based on specific criteria.
This article explores different methods for achieving this in Scala.
Table of Content
- 1. Using `splitAt`:
- 2. Using `slice` :
- 3. Splitting by Delimiter :
- 4. Splitting by Condition :
- Choosing the Right Method:
Contact Us