C # string interrupts every n characters

Suppose I have a line with the text: “THIS IS A TEST”. How would I divide it into all n characters? So if n is 10, then it will display:

"THIS IS A " "TEST" 

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

Any help would be appreciated.

+6
source share
5 answers

Let me borrow an implementation from my answer in a code review. This inserts a line breaking each n characters:

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

Edit:
Instead, return an array of strings:

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

Perhaps this can be used to handle extremely extreme 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 commonly used TextReader . You can process very large text files (IIS log files, SharePoint log files, etc.) without downloading the entire file, but reading it line by line.

+3
source

You can use 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()); 

See this question for more details:
Splitting a string into pieces of a certain size

+2
source

This is probably not the most optimal way, but without a regular expression:

 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())); 
+1
source

Going back to this after looking at the code, there is another way to do 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)); } } 
+1
source

Source: https://habr.com/ru/post/899299/


All Articles