How to format an array of strings in lines with maxWidth without breaking the words in Scala

1 Answer

0 votes
object WordWrap {

  def formatLines(words: List[String], maxWidth: Int): List[String] = {
    var result = List.empty[String]
    var currentLine = ""
    var currentLength = 0

    for (word <- words) {
      val wordLen = word.length

      // If adding this word exceeds maxWidth, push current line
      if (currentLength + (if (currentLine.isEmpty) 0 else 1) + wordLen > maxWidth) {
        if (currentLine.nonEmpty) {
          result = result :+ currentLine
        }
        currentLine = word
        currentLength = wordLen
      } else {
        if (currentLine.nonEmpty) {
          currentLine += " "
          currentLength += 1
        }
        currentLine += word
        currentLength += wordLen
      }
    }

    // Push the last line if not empty
    if (currentLine.nonEmpty) {
      result = result :+ currentLine
    }

    result
  }

  def main(args: Array[String]): Unit = {
    val words = List("This", "is", "a", "programming", "example", "of", "text", "wrapping")
    val maxWidth = 12

    val lines = formatLines(words, maxWidth)

    for (line <- lines) {
      println(s""""$line"""")
    }
  }
}



/*
run:

"This is a"
"programming"
"example of"
"text"
"wrapping"

*/

 



answered Dec 2, 2025 by avibootz

Related questions

...