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.

Jacek Laskowski
  • 72,696
  • 27
  • 242
  • 420
MartinStettner
  • 28,719
  • 15
  • 79
  • 106

2 Answers2

78
scala> val grouped = "Thequickbrownfoxjumps".grouped(4).toList
grouped: List[String] = List(Theq, uick, brow, nfox, jump, s)
michael.kebe
  • 10,916
  • 3
  • 44
  • 62
  • `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
  • 413
  • 2
  • 19