/*
This program wraps a string into lines of maximum width w.
Method:
- Split the input text into words using String.Split().
- 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 StringBuilder for efficient string construction.
*/
using System;
using System.Text;
class WrapTextDemo
{
// Function that wraps text into lines of width w
static string WrapText(string text, int w)
{
string[] words = text.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
StringBuilder line = new StringBuilder();
StringBuilder result = new StringBuilder();
foreach (string word in 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.AppendLine(line.ToString());
line.Clear();
line.Append(word);
}
}
}
// Add the final line
if (line.Length > 0) {
result.Append(line.ToString());
}
return result.ToString();
}
static void Main()
{
string sample =
"C# provides useful built-in tools for handling strings. " +
"This program demonstrates how to wrap text cleanly and efficiently.";
string wrapped = WrapText(sample, 35);
Console.WriteLine(wrapped);
}
}
/*
run:
C# provides useful built-in tools
for handling strings. This program
demonstrates how to wrap text
cleanly and efficiently.
*/