Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- private static string Balance(string text, int singleLineMaxLength = 42)
- {
- // the quick grown fox jumps over a lazy dog! the quick grown fox jumps over a lazy dog! the quick grown fox jumps over a lazy dog!
- // note: the text won't have any tag!
- // find first white-space going backward (ignore tags)
- // find first white-space going forward (ignore tags)
- var len = text.Length;
- var sb = new StringBuilder();
- var from = 0;
- var lineCount = len / singleLineMaxLength;
- // calculate the amount of line required to fit all the text basing on the maximum single line length
- // var lineCount = Math.Round(len / Convert.ToDouble(singleLineMaxLength), MidpointRounding.AwayFromZero);
- const char whiteSpace = ' ';
- for (var i = 0; i < lineCount; i++)
- {
- // 1. calculate the pivot position (where the 'pivot' will be place to start looking for back/forth white-space index).
- // 2. (x) + 1 : if the pivot is in a position that is not white-space we want to jump once
- // so after we start looking to find it with 'prePivotWhiteSpace--'
- // but after adding the find for white-space in front it's not requited anymore
- // 3. (i + 1) is to move 'singleLineMaxLength' to the next position of same length to handle second line.
- var pivot = singleLineMaxLength * (i + 1) + 1;
- // find first whitespace before pivot
- var prePivotWhiteSpace = pivot;
- while (prePivotWhiteSpace > 0 && text[prePivotWhiteSpace] != whiteSpace) prePivotWhiteSpace--;
- // find first white-space after pivot
- var postPivotWhiteSpace = pivot;
- while (postPivotWhiteSpace < len && text[postPivotWhiteSpace] != whiteSpace) postPivotWhiteSpace++;
- // get closest point to pivot/avg position
- var splitPosition = Math.Abs(pivot - prePivotWhiteSpace) < Math.Abs(pivot - postPivotWhiteSpace)
- ? prePivotWhiteSpace
- : postPivotWhiteSpace;
- // store text
- // note: this will require trimming the end to remove last line if +2 line were appended
- sb.AppendLine(text.Substring(from, splitPosition - from));
- // calculate next from
- from = splitPosition + 1;
- }
- // handle the remaining if any
- if (from < len)
- {
- sb.Append(text[from..]);
- }
- return sb.ToString();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement