/**
This program wraps a string into lines of maximum width `w`.
Method:
- Use String.split() to break the text into words.
- Build each line until adding another word would exceed the width.
- When the limit is reached, store the line and begin a new one.
- Uses standard library features such as StringBuilder for efficient concatenation.
*/
public class WrapTextProgram {
// Function that wraps text into lines of width w
public static String wrapText(String text, int w) {
String[] words = text.split("\\s+"); // Split on whitespace
StringBuilder line = new StringBuilder();
StringBuilder result = new StringBuilder();
for (String word : words) {
// If line is empty, start it with the word
if (line.length() == 0) {
line.append(word);
}
else {
// Check if adding the next word exceeds width
if (line.length() + 1 + word.length() <= w) {
line.append(" ").append(word);
} else {
// Store the completed line
result.append(line).append("\n");
line.setLength(0); // Clear the line
line.append(word);
}
}
}
// Add the final line
if (line.length() > 0) {
result.append(line);
}
return result.toString();
}
public static void main(String[] args) {
String sample =
"Java provides useful built-in tools for handling strings. "
+ "This program demonstrates how to wrap text cleanly and efficiently.";
String wrapped = wrapText(sample, 35);
System.out.println(wrapped);
}
}
/*
run:
Java provides useful built-in tools
for handling strings. This program
demonstrates how to wrap text
cleanly and efficiently.
*/