Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Line break a string on x number of characters but not through a word

I'll try to explain what I am looking for as best as I can. Currently, I am using this code to line break every x number of characters.

public static string SpliceText(string text, int lineLength)
    {
        return Regex.Replace(text, "(.{" + lineLength + "})", "$1" + Environment.NewLine);

    }

This works great, but often it will break every x number and obviously will sometimes break through a word. Is it possible for code to check if it is breaking mid-word, and if it's not mid-word to break anyways but now check if the first character after the break is a space and remove it if so?

I know I am asking for a lot, but thanks in advance anyways!

like image 901
user2416047 Avatar asked Dec 11 '22 14:12

user2416047


1 Answers

Try this:

public static string SpliceText(string text, int lineLength)
{
    var charCount = 0;
    var lines = text.Split(new string[] {" "}, StringSplitOptions.RemoveEmptyEntries)
                    .GroupBy(w => (charCount += w.Length + 1) / lineLength)
                    .Select(g => string.Join(" ", g));

    return String.Join("\n", lines.ToArray());
}

Here's my screen shot for this: enter image description here

like image 130
roybalderama Avatar answered Apr 28 '23 20:04

roybalderama