Search code examples
c#splitlinecharacter

C# line break every n characters


Suppose I have a string with the text: "THIS IS A TEST". How would I split it every n characters? So if n was 10, then it would display:

"THIS IS A "
"TEST"

..you get the idea. The reason is because I want to split a very big line into smaller lines, sort of like word wrap. I think I can use string.Split() for this, but I have no idea how and I'm confused.

Any help would be appreciated.


Solution

  • Let's borrow an implementation from my answer on code review. This inserts a line break every n characters:

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

    Edit:
    To return an array of strings instead:

    public static string[] SpliceText(string text, int lineLength) {
      return Regex.Matches(text, ".{1," + lineLength + "}").Cast<Match>().Select(m => m.Value).ToArray();
    }