RosettaCodeData/Task/Word-wrap/Groovy/word-wrap-3.groovy
2017-09-25 22:28:19 +02:00

6 lines
238 B
Groovy

String wordWrap(str, width=80) {
str.tokenize(' ').inject([[]]) { rows, word ->
if (rows.last().join(' ').length() + word.length() <= width) rows.last() << word else rows << [word]
rows
}.collect { it.join(' ') }.join('\n')
}