Word Wrap
Level: IntermediateConcepts: Strings
Create a program that wraps text at a specified column width.
Requirements
- Implement text wrapping rules:
              - Break text at word boundaries when possible
- Break words only if they exceed the column width
- Preserve whitespace between words
- Handle multiple spaces and tabs
 
- Handle edge cases:
              - Empty input
- Input shorter than column width
- Words longer than column width
- Multiple consecutive spaces
 
- Return appropriate results:
              - Wrapped text as a string
- Error message for invalid inputs
 
Test Cases
| Input | Column Width | Expected Output | Notes | 
|---|---|---|---|
| "Hello" | 5 | "Hello" | No wrapping needed | 
| "Hello World" | 5 | "Hello\nWorld" | Break at word boundary | 
| "Hello World" | 7 | "Hello\nWorld" | Break at word boundary | 
| "Hello World" | 20 | "Hello World" | No wrapping needed | 
| "Supercalifragilisticexpialidocious" | 10 | "Supercalif\nragilisti\ncexpiali\ndocious" | Break long word | 
| "Hello World" | 5 | "Hello\nWorld" | Handle multiple spaces | 
Edge Cases to Consider
- Empty string
- Null input
- Zero or negative column width
- Very long words
- Multiple consecutive spaces or tabs
- Text with line breaks
Tips
- Start with simple cases (no wrapping needed)
- Add word boundary breaking next
- Then handle long words
- Finally add whitespace handling
- Consider using regular expressions for word boundaries