How would you write a funcitonal implementation for split(positions:List[Int], str:String):List[String]
, which is similar to splitAt
but splits a given string into a list of strings by a given list of positions?
For example
split(List(1, 2), "abc")
returns List("a", "b", "c")
split(List(1), "abc")
returns List("a", "bc")
split(List(), "abc")
returns List("abc")
Scala List splitAt() method with example. The splitAt() method belongs to the value member of the class List. It is utilized to split the given list into a prefix/suffix pair at a stated position. Where, n is the position at which we need to split.
To split a string at a specific index, use the slice method to get the two parts of the string, e.g. str. slice(0, index) returns the part of the string up to, but not including the provided index, and str. slice(index) returns the remainder of the string. Copied!
You can split a string by each character using an empty string('') as the splitter. In the example below, we split the same message using an empty string. The result of the split will be an array containing all the characters in the message string.
def lsplit(pos: List[Int], str: String): List[String] = {
val (rest, result) = pos.foldRight((str, List[String]())) {
case (curr, (s, res)) =>
val (rest, split) = s.splitAt(curr)
(rest, split :: res)
}
rest :: result
}
Something like this:
def lsplit(pos: List[Int], s: String): List[String] = pos match {
case x :: rest => s.substring(0,x) :: lsplit(rest.map(_ - x), s.substring(x))
case Nil => List(s)
}
(Fair warning: not tail recursive so will blow the stack for large lists; not efficient due to repeated remapping of indices and chains of substrings. You can solve these things by adding additional arguments and/or an internal method that does the recursion.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With