[英]How to split string into equal-length substrings?
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). 我在Scala中寻找一种优雅的方式将给定的字符串拆分为固定大小的子串(序列中的最后一个字符串可能更短)。
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. 当然,我可以简单地使用一个循环,但必须有一个更优雅(功能样式)的解决方案。
scala> val grouped = "Thequickbrownfoxjumps".grouped(4).toList
grouped: List[String] = List(Theq, uick, brow, nfox, jump, s)
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")
\***************************************************************************/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.