简体   繁体   中英

split a line of text into two lines using a <br> in c#

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?

You can use IndexOf instead of looping through the string yourself.

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;

    pos = input.IndexOf(' ', pos);

    return input.Substring(0, pos) + "<br/>" + input.Substring(pos + 1);
}

A possible improvement would be something along the lines of

private const MinimumLengthForBreak = 12;
private const LineBreakString = "<br />";

public static string BreakLineIntoTwo(this HtmlHelper helper, string input)
{
    if (string.IsNullOrEmpty(input)) return string.Empty;
    if (input.Length < MinimumLengthForBreak ) return input;

    int pos = input.IndexOf(' ', input.Length / 2);
    if (pos < 0) return input; // No space found, not checked in original code

    return input.Substring(0, pos) + LineBreakString + input.Substring(pos + 1);
}

Note: Syntax not checked since i'm at work and can't check atm.

Why don't you use css property of word-wrap .

With word-wrap property,you can force long text to wrap in a new line by specifying break-word.

Check this example

Best Regards
Myra

a shorter version of what you had using 'IndexOf' and 'Insert':

    private string BreakLineIntoTwo(string input)
    {
        if (string.IsNullOrEmpty(input)) return string.Empty;
        if (input.Length < 12) return input;          

       int index = input.IndexOf(" ", input.Length/2);

       return index > 0 ? input.Insert(index, "<br />") : input;
    }

I did this as a separate method but you should be able to easily change this into your extension method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM