Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,623 questions

55,358 answers

573 users

How to wrap a string into lines of width w in Scala

1 Answer

0 votes
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.

*/

 



answered Jul 11 by avibootz
...