Scala 字符串拆分为递减的 char 数量

Scala string splitting in decending amounts of char

给定一个字符串,例如

val s = (0 to 9).mkString
s: String = 0123456789

努力寻找一种实用的(整洁的)方法来获得这样的 Array[String]

Array("0123", "456", "78", "9")

在预先计算的索引上使用 substring 证明相当混乱。

更新数组大小n和字符串长度l总是相关的,

val l = n*(n+1)/2

换句话说,n = 1,2,... 的输入字符串的长度为 1,3,6,10,15,... 因此,正如@m-z 所指出的,字符串如 0123456789a无解

您可以尝试使用 Iterator:

Iterator.from(0).map { i => 
    s.dropRight(i*(i+1)/2).takeRight(i+1)
}.takeWhile(!_.isEmpty).toList.reverse

或递归:

def incSplit(s: String, iter: Int = 1): List[String] = s match {
    case "" => Nil
    case s => incSplit(s.dropRight(iter), iter + 1) :+ s.takeRight(iter)
}

这是另一个解决方案

  val s = "0123456789" 
  (4 to 1 by -1).foldLeft((s,List[String]()))
                         {case ((t, res), n) => 
                            (t.drop(n), t.take(n)::res)}
                ._2
                .reverse

每次我们从字符串中取出前 n 个字符,将其添加到结果并将字符串(减去前 n 个字符)传递给下一次迭代

编辑:到目前为止所有的答案都很丑陋。所以这是一个更优雅的 (IMO)

val s = "0123456789"
    //> s  : String = 0123456789
val indicies = (4 to 1 by -1).scanLeft(0) {_ + _}
    //> indicies  : List[Int] = List(0, 4, 7, 9, 10)
val slices = indicies zip indicies.tail   
    //> slices  : List[(Int, Int)] = List((0,4), (4,7), (7,9), (9,10))
for ((start,end) <- slices) yield s.slice(start, end)
    //> res1: List[String] = List(0123, 456, 78, 9)