Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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")
like image 339
Michael Avatar asked Nov 28 '11 17:11

Michael


People also ask

How do you split a list in Scala?

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.

How do I split a string in a specific position?

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!

How do I split a string into multiple parts?

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.


2 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
}
like image 177
Marimuthu Madasamy Avatar answered Oct 07 '22 13:10

Marimuthu Madasamy


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

like image 26
Rex Kerr Avatar answered Oct 07 '22 13:10

Rex Kerr