如何将字符串拆分为等长子串?

时间:2010-09-13 10:52:35

标签: scala functional-programming split

我在Scala中寻找一种优雅的方法,将给定的字符串拆分为固定大小的子字符串(序列中的最后一个字符串可能更短)。

所以

split("Thequickbrownfoxjumps", 4)

应该产生

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

当然我可以简单地使用一个循环,但必须有一个更优雅(功能风格)的解决方案。

2 个答案:

答案 0 :(得分:61)

scala> val grouped = "Thequickbrownfoxjumps".grouped(4).toList
grouped: List[String] = List(Theq, uick, brow, nfox, jump, s)

答案 1 :(得分:1)

像这样:

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


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