28

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.

Jacek Laskowski
  • 68,975
  • 24
  • 224
  • 395
MartinStettner
  • 28,001
  • 14
  • 77
  • 104

2 Answers2

74
scala> val grouped = "Thequickbrownfoxjumps".grouped(4).toList
grouped: List[String] = List(Theq, uick, brow, nfox, jump, s)
michael.kebe
  • 10,500
  • 3
  • 43
  • 59
  • `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 – WestCoastProjects Mar 22 '18 at 01:45
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")


\***************************************************************************/
xyz
  • 402
  • 2
  • 16