代码之家  ›  专栏  ›  技术社区  ›  MartinStettner

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

  •  25
  • MartinStettner  · 技术社区  · 14 年前

    我在找一个 优雅的 在路上 Scala 将给定的字符串拆分成固定大小的子字符串(序列中的最后一个字符串可能更短)。

    所以

    split("Thequickbrownfoxjumps", 4)
    

    应该屈服

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

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

    2 回复  |  直到 7 年前
        1
  •  61
  •   michael.kebe    9 年前
    scala> val grouped = "Thequickbrownfoxjumps".grouped(4).toList
    grouped: List[String] = List(Theq, uick, brow, nfox, jump, s)
    
        2
  •  1
  •   xyz    7 年前

    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")
    
    
    \***************************************************************************/