Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# Best way to break up a long string

This question is not related to:

Best way to break long strings in C# source code

Which is about source, this is about processing long outputs. If someone enters:

WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW

As a comment, it breaks the container and makes the entire page really wide. Is there any clever regexp that can say, define a maximum word length of 20 chars and then force a whitespace character?

Thanks for any help!

like image 402
Tom Gullen Avatar asked Dec 21 '22 15:12

Tom Gullen


1 Answers

There's probably no need to involve regexes in something this simple. Take this extension method:

public static string Abbreviate(this string text, int length) {
    if (text.Length <= length) {
        return text;
    }

    char[] delimiters = new char[] { ' ', '.', ',', ':', ';' };
    int index = text.LastIndexOfAny(delimiters, length - 3);

    if (index > (length / 2)) {
        return text.Substring(0, index) + "...";
    }
    else {
        return text.Substring(0, length - 3) + "...";
    }
}

If the string is short enough, it's returned as-is. Otherwise, if a "word boundary" is found in the second half of the string, it's "gracefully" cut off at that point. If not, it's cut off the hard way at just under the desired length.

If the string is cut off at all, an ellipsis ("...") is appended to it.

If you expect the string to contain non-natural-language constructs (such as URLs) you 'd need to tweak this to ensure nice behavior in all circumstances. In that case working with a regex might be better.

like image 69
Jon Avatar answered Dec 29 '22 00:12

Jon