RosettaCodeData/Task/Word-wrap/Groovy/word-wrap-3.groovy
2023-07-01 13:44:08 -04: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')
}