C# line break every n characters

19,922

Solution 1

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();
}

Solution 2

Maybe this can be used to handle efficiently extreme large files :

public IEnumerable<string> GetChunks(this string sourceString, int chunkLength)
{  
    using(var sr = new StringReader(sourceString))
    {
        var buffer = new char[chunkLength];
        int read;
        while((read= sr.Read(buffer, 0, chunkLength)) == chunkLength)
        {
            yield return new string(buffer, 0, read);
        }        
    }
}

Actually, this works for any TextReader. StreamReader is the most common used TextReader. You can handle very large text files (IIS Log files, SharePoint Log files, etc) without having to load the whole file, but reading it line by line.

Solution 3

You should be able to use a regex for this. Here is an example:

//in this case n = 10 - adjust as needed
List<string> groups = (from Match m in Regex.Matches(str, ".{1,10}") 
                       select m.Value).ToList();

string newString = String.Join(Environment.NewLine, lst.ToArray());

Refer to this question for details:
Splitting a string into chunks of a certain size

Solution 4

Probably not the most optimal way, but without regex:

string test = "my awesome line of text which will be split every n characters";
int nInterval = 10;
string res = String.Concat(test.Select((c, i) => i > 0 && (i % nInterval) == 0 ? c.ToString() + Environment.NewLine : c.ToString()));

Solution 5

Coming back to this after doing a code review, there's another way of doing the same without using Regex

public static IEnumerable<string> SplitText(string text, int length)
{
    for (int i = 0; i < text.Length; i += length)
    {
        yield return text.Substring(i, Math.Min(length, text.Length - i));  
    }
}
Share:
19,922
dnclem
Author by

dnclem

Updated on June 26, 2022

Comments

  • dnclem
    dnclem almost 2 years

    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.

  • Jeff Mercado
    Jeff Mercado over 12 years
    It's better to use String.Concat() instead of a join with an empty string.
  • Jack Miller
    Jack Miller almost 3 years
    The general idea is good but isn't this approach missing the last characters if source.Length is not a multiple of chunkLength?
  • 我零0七
    我零0七 over 2 years
    If you want to read all string(include last string which length is less than chunkLength),just use this condition:while ((read = sr.Read(buffer, 0, chunkLength)) !=0)