I have the following code (inherited!) that will split a line of text into 2 lines with a html line break <br/>.
public static string BreakLineIntoTwo(this HtmlHelper helper, string input)
{
if (string.IsNullOrEmpty(input)) return string.Empty;
if (input.Length < 12) return input;
int pos = input.Length / 2;
while ((pos < input.Length) && (input[pos] != ' '))
pos++;
if (pos >= input.Length) return input;
return input.Substring(0, pos) + "<br/>" + input.Substring(pos + 1);
}
The rules seem to be if the line of text is less than 12 characters then just return it. If not find the middle of the text and move along to the next space and insert a line break. We can also assume that there are no double spaces and no additional spaces at the end and the the text is not just one long line of letters abcdefghijkilmnopqrstuvwxyz etc.
This seems to work fine and my question is Is there a more elegant approach to this problem?
A possible improvement would be something along the lines of
Note: Syntax not checked since i’m at work and can’t check atm.