object TextWrapper {
/**
* Wraps a string into lines of maximum width `w`.
*
* @param text The input string to wrap.
* @param w Maximum width of each line.
* @return A sequence of wrapped lines.
*/
def wrap(text: String, w: Int): Seq[String] = {
// Split the text into words. This avoids breaking words in the middle.
val words = text.split("\\s+")
// A buffer to accumulate the final lines.
val lines = scala.collection.mutable.ListBuffer[String]()
// A StringBuilder to construct the current line.
val currentLine = new StringBuilder
for (word <- words) {
// If adding this word exceeds the width, finalize the current line.
if (currentLine.nonEmpty && currentLine.length + 1 + word.length > w) {
lines += currentLine.toString()
currentLine.clear()
}
// Add the word to the current line (with a space if needed).
if (currentLine.nonEmpty) currentLine.append(" ")
currentLine.append(word)
}
// Add the last line if it contains anything.
if (currentLine.nonEmpty) {
lines += currentLine.toString()
}
lines.toSeq
}
def main(args: Array[String]): Unit = {
val text =
"Scala is a powerful language that blends object-oriented and functional programming."
val width = 25
val wrapped = wrap(text, width)
println(s"Wrapped text (width = $width):")
wrapped.foreach(println)
}
}
/*
run:
Wrapped text (width = 25):
Scala is a powerful
language that blends
object-oriented and
functional programming.
*/