Skip to content

Instantly share code, notes, and snippets.

@scottoffen
Created February 13, 2019 16:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scottoffen/4aaf0db940e63f4b2637b79a19651e2b to your computer and use it in GitHub Desktop.
Save scottoffen/4aaf0db940e63f4b2637b79a19651e2b to your computer and use it in GitHub Desktop.
public class ParagraphBuilder
{
public const int DefaultColumns = 86;
private string _input;
private int _columns;
private int _remaining;
private List<string> _output = new List<string>();
private List<string> _line = new List<string>();
private List<char> _word = new List<char>();
public ParagraphBuilder(string input, int columns = DefaultColumns)
{
_input = input;
_columns = columns;
_remaining = columns;
ParseInput();
}
private void ParseInput()
{
if (string.IsNullOrEmpty(_input)) return;
foreach (var chr in _input.ToCharArray())
{
if (char.IsWhiteSpace(chr))
{
AddWordToLine();
}
else
{
_word.Add(chr);
}
}
AddWordToLine();
AddLineToOutput();
}
private void AddWordToLine()
{
if (_word.Count == 0) return;
var word = string.Concat(_word);
// Is there room on the line?
if (_remaining >= _word.Count)
{
_line.Add(word);
_remaining -= (_word.Count + 1);
}
// Is the word hyphenated and can the first part fit?
else if (_word.Contains('-') && _remaining >= (_word.IndexOf('-') + 1))
{
var parts = word.Split("-", 2);
_line.Add(parts[0]);
AddLineToOutput();
_line.Add(parts[1]);
_remaining -= (parts[1].Length + 1);
}
else
{
AddLineToOutput();
_line.Add(word);
}
_word.Clear();
}
private void AddLineToOutput()
{
if (_line.Count == 0) return;
_output.Add(string.Join(" ", _line));
_line.Clear();
_remaining = _columns;
}
public override string ToString()
{
return string.Join(Environment.NewLine, _output);
}
}
@scottoffen
Copy link
Author

Converts a long string into a paragraph with breaks at the column width specified.
TODO:

  • Break strings that are too long for the column width

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment