/*
This program wraps a string into lines of maximum width w.
Method:
- Split the input text into words using split_whitespace().
- 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 String and Vec<String> for clear and efficient processing.
*/
fn wrap_text(text: &str, w: usize) -> String {
let words: Vec<&str> = text.split_whitespace().collect();
let mut line = String::new();
let mut result: Vec<String> = Vec::new();
for word in words {
let word_len = word.len();
// If line is empty, start it with the word
if line.is_empty() {
line.push_str(word);
} else {
// Check if adding the next word exceeds width
if line.len() + 1 + word_len <= w {
line.push(' ');
line.push_str(word);
} else {
// Store the completed line
result.push(line);
line = String::from(word);
}
}
}
// Add the final line
if !line.is_empty() {
result.push(line);
}
result.join("\n")
}
fn main() {
let sample =
"Rust provides useful built-in tools for handling strings. \
This program demonstrates how to wrap text cleanly and efficiently.";
let wrapped = wrap_text(sample, 35);
println!("{}", wrapped);
}
/*
run:
Rust provides useful built-in tools
for handling strings. This program
demonstrates how to wrap text
cleanly and efficiently.
*/