Whilst I can find MANY examples of how to split a string based on a certain character within that string, how can I split a string based on the no of chars

For example, I have a string that is 20 chars long but I want to create a newline every 5 chars;

string str = 12345678901234567890;

for (i = 0, i < 5, i++]
{
    textBox1.Text = str;
    textBox1.EnvironmentNewline;
}

Any help is greatly appreciated

Line 1: a string litteral is always placed between quotes, so this line should read:

string str = "12345678901234567890";

Line 3 should end in a round bracket

for (int i = 0; i < 5; i++)

Look here you want to insert something into a string.

static void Main() {
    Regex r = new Regex("(.){0,20}");
    String s = "1234567890123456789a1234567890123456789b12345c";
    StringBuilder sb = new StringBuilder();

    MatchCollection m = r.Matches(s);
    foreach (Match ma in m) {
        sb.Append(ma.Value);
        sb.Append("\n");
    }

    Console.WriteLine(sb.ToString());
    Console.ReadLine();
}

Change the 20 in the Regex to whatever length you want. sb.ToString() gives you the final string.

Edited 6 Years Ago by Momerath: n/a

Thanks Momerath, the code worked a treat once I entered

using System.Text.RegularExpressions;

at the beginning of the code.

Edited 6 Years Ago by buster2209: n/a

This question has already been answered. Start a new discussion instead.