scala - 多线字符串拆分 [英] scala - muliline string split
本文介绍了scala - 多线字符串拆分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个:
val msg = "Preparado para cocinar..."
val message = msg.splitAt(msg.length()/2)
println(message._1 + "\n" + message._2.trim())
问题是我得到了这个结果(bcz我只是在中间分割它):
The problem is that I am getting this result (bcz I am just spliting it at the middle):
Preparado pa
ra cocinar...
如何显示多条消息(不仅是两部分),但应该用空格
分隔,而不是在句子中间?
How I can have a multi(not only in 2 parts) displayed message but it should be separated in spaces
not in the middle of the sentence?
推荐答案
一个相当优雅的函数式解决方案
A reasonably elegant functional solution
def wordWrap(s: String, n: Int) = s.split("\\s").foldLeft(List[String]())
{ (lines, word) =>
if (lines.isEmpty || lines.head.length + word.length + 1 > n)
word :: lines
else
(lines.head + " " + word) :: lines.tail
}
.reverse
wordWrap( "Preparado para cocinar...", 23)
// List(Preparado para, cocinar...)
wordWrap( "Preparado para cocinar...", 5)
// List(Preparado, para, cocinar...)
wordWrap("A quick brown fox jumps over the lazy dog.", 10)
// List(A quick, brown fox, jumps over, the lazy, dog. )
只检查一次空列表的变体
A variant that just checks the empty list once
def wordWrap(s: String, n: Int) = {
val words = s.split("\\s")
if (words.isEmpty) Nil
else
words.tail.foldLeft(List[String](words.head)){ (lines, word) =>
if (lines.head.length + word.length + 1 > n)
word :: lines
else
(lines.head + " " + word) :: lines.tail
}.reverse
}
这篇关于scala - 多线字符串拆分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文