30

Im looking for an elegant way in Scala to split a given string into substrings of fixed size (the last string in the sequence might be shorter).

So

split("Thequickbrownfoxjumps", 4)

should yield

["Theq","uick","brow","nfox","jump","s"]

Of course I could simply use a loop but there has to be a more elegant (functional style) solution.

2 Answers 2

78
scala> val grouped = "Thequickbrownfoxjumps".grouped(4).toList
grouped: List[String] = List(Theq, uick, brow, nfox, jump, s)
Sign up to request clarification or add additional context in comments.

1 Comment

grouped .. somehow I can't "hang on" to that method name - keep needing to look it up again: especially since thinking of partitition - which is a predicate based splitting
2

Like this:

def splitString(xs: String, n: Int): List[String] = {
  if (xs.isEmpty) Nil
  else {
    val (ys, zs) = xs.splitAt(n)
    ys :: splitString(zs, n)
  }
}

splitString("Thequickbrownfoxjumps", 4)
/************************************Executing-Process**********************************\
(   ys     ,      zs          )
  Theq      uickbrownfoxjumps
  uick      brownfoxjumps
  brow      nfoxjumps
  nfox      jumps
  jump      s
  s         ""                  ("".isEmpty // true)


 "" :: Nil                    ==>    List("s")
 "jump" :: List("s")          ==>    List("jump", "s")
 "nfox" :: List("jump", "s")  ==>    List("nfox", "jump", "s")
 "brow" :: List("nfox", "jump", "s") ==> List("brow", "nfox", "jump", "s")
 "uick" :: List("brow", "nfox", "jump", "s") ==> List("uick", "brow", "nfox", "jump", "s")
 "Theq" :: List("uick", "brow", "nfox", "jump", "s") ==> List("Theq", "uick", "brow", "nfox", "jump", "s")


\***************************************************************************/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.