Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 575
rayanisran Avatar asked Oct 14 '11 13:10

rayanisran


1 Answers

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();
}
like image 195
Guffa Avatar answered Sep 20 '22 15:09

Guffa