How to split a line given a list of positions in Scala

How could you write a functional 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 specified list of positions?

for instance

  • split(List(1, 2), "abc") returns List("a", "b", "c")
  • split(List(1), "abc") returns List("a", "bc")
  • split(List(), "abc") returns List("abc")
+6
source share
3 answers
 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 } 
+4
source

Something like that:

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

(A fair warning: it is not tail recursive, so it will hit the stack for large lists, inefficient due to reassigning indices and strings of substrings. You can solve these things by adding additional arguments and / or an internal method that does recursions.)

+4
source

What about....

 def lSplit( indices : List[Int], s : String) = (indices zip (indices.tail)) map { case (a,b) => s.substring(a,b) } scala> lSplit( List(0,4,6,8), "20131103") List[String] = List(2013, 11, 03) 
+2
source

Source: https://habr.com/ru/post/902582/


All Articles