I saw examples in various languages, but for c # I did not understand how to implement it, I ask for help. There is a text, for example 20 characters. How to make a line break after 10 characters for example? Thank.

  • and in other languages ​​how was this implemented? :) - Grundy
  • @Grundy if you know the answer, why don't you just help me? - Dmitry
  • one
    Regex.Replace(str, "(?<=\\G.{10})(?=.)", "\n") - PetSerAl
  • @PetSerAl, how effective is the preview back? - Qwertiy
  • 2
    sudden codegolf? - VladD

8 answers 8

The easiest way to write code is to use regular expressions: http://ideone.com/rbR09w

 public static string SplitToLines(string str, int n) { return Regex.Replace(str, ".{"+n+"}(?!$)", "$0\n"); } 
  • The most correct code, in my opinion) - Egor Trutnev

Another option:

 string text = "абвгдеёжзиийклмн"; int k = 10, i = text.Length; text = text.Substring(0, k) + "\n" + text.Substring(k+1, ik-1); 

By tym32167 :

 text = text.Substring(0, k) + Environment.NewLine + text.Substring(k + 1, i - k - 1); 
  • And if there are more than two lines? - Qwertiy
  • @Qwertiy questioner asked about the transfer in the singular - Egor Trutnev
  • Hmm .. Not paying attention to this moment. Then yes, a good decision :) - Qwertiy
  • one
    Rekvestrovuyu replacement \n on Environment.NewLine :) - tym32167

A good way to capture performance is StringBuilder: http://ideone.com/Mmnvjp

 public static string SplitToLines(string str, int n) { var sb = new StringBuilder(str.Length + (str.Length + 9) / 10); for (int q=0; q<str.Length; ) { sb.Append(str[q]); if (++q % n == 0) sb.AppendLine(); } if (str.Length % n == 0) --sb.Length; return sb.ToString(); } 
  • Well, why so. insert into a line after the desired character or who has not canceled - rdorn
  • @rdorn, Insert in StringBuilder will move the entire tail each time, and in the string it will generally copy the entire string. In both cases, the asymptotics will be quadratic, and in my solution, linear. - Qwertiy
  • I need to get into the sources ... I don’t think that everything is so bad there, although ... I ’ve gotten shorter, to watch - rdorn
  • referencesource.microsoft.com/mscorlib/R/61f8c55c63613daf.html in. There is also linear speed, and it seems that the copying itself uses unmanaged code. In the case of multiple inserts (every N characters), I would also use this option, but for a single case, the native insert is better - rdorn
  • @rdorn, copying with unmanaged code still copies the entire line. With strings, exactly quadratic asymptotics. With the new implementation of StringBuilder on linked lists, maybe not quadratic, but still something will move on each iteration. - Qwertiy

This option ...

 using static System.Console; class Program { public static string Insert_LF_n(string s, int n) { char[] c = new char[s.Length + s.Length / n]; int i = 0, j = 1; foreach(char ch in s) { c[i++] = ch; if(j++ % n == 0) { c[i++] = '\n'; j = 1; } } // если последний символ - "перевод строки" - удаляем. if (c[i - 1] == '\n') i--; return new string(c, 0, i); } static void Main(string[] args) { string s = "kjabdjlirujl;qkmrghwiureh;alksngk;jhdriughjksndv.ma'pjkrdoigkdfjnvsdlkjfp'iowjoeijrlkdjflk"; WriteLine(s); Write('\n' + Insert_LF_n(s, 10)); ReadKey(); } } 
  • If the length of the string is a multiple of 10, then an extra line feed is added to the end. And so, I like it :) - Qwertiy
  • one
    Now deletes the line feed) - Victor Predko
  • Tested runtime, StringBuilder is the fastest: Runtime of 100000 repetitions of the function: Insert_LF_n (via char [] array): 221 ms, SplitToLinesByQwertiy (Regex): 664 ms, SplitToLinesByChloroform (StringBuilder): 156 ms - Victor Pedko 66 ms - Victor Pedko ms, 566 ps.
  • Strange. In theory, the array should be faster. - Qwertiy
  • @Qwertiy, you can see the machine code there. The results are averaged over 10
 string myString = "My very long string......................................."; string rn = Environment.NewLine; int offset = 10; StringBuilder sb = new StringBuilder(myString); for (int i = 1; i <= myString.Length / offset; i++) { sb.Insert(i * offset + (i - 1) * rn.Length, rn); } Console.WriteLine(sb.ToString()); 

Made through StringBuilder , should work better with a very large string length.

    Somehow it happened

     int countOnOneLine = 10; string testStr = "123456789D123456789D1111"; string resultStr = ""; for (int i = 1; i <= testStr.Length; i++) { if (i % countOnOneLine == 0) resultStr += testStr[i - 1] + Environment.NewLine; else resultStr += testStr[i - 1]; } Console.WriteLine(resultStr); Console.ReadLine(); 

    PS: something tells me that there is a more appropriate solution ...

    • five
      StringBuilder ... - Qwertiy

    We start the cycle from the initial position and insert the necessary line each time. We move on 10 + the size of the inserted line. Etc.

    Using:

     var result = InsertEach(source, Environment.NewLine, 10); 

    Method:

     public static string InsertEach(string source, string insertValue, int interval) { var lengthOfNewLine = insertValue.Length; for (var i = interval; i < source.Length; i += interval + lengthOfNewLine) { source = source.Insert(i, insertValue); } return source; } 

    Test !

    • And here the quadratic asymptotics. - Qwertiy
    • @Qwertiy, and what is the asymptotics for a replacement through regexps? - Andrew NOP
    • @ Andrei, I do not know. I think they have optimized the replacement itself, so in my version it will turn out to be linear with rather bold overheads. But I can't evaluate the regular calendar from the commentary (the one in which the preview is back). - Qwertiy

    My version of Regex)

      static void Main(string[] args) { Console.WriteLine(Regex()); Console.WriteLine(Iteration()); Console.ReadKey(); } static string Regex() { string pattern = @"(.{0,10})"; string input = "qwertyuiopqqwertyuiopqwertyuiopwertyuio"; string replacement = "$1\n"; Regex rgx = new Regex(pattern); string result = rgx.Replace(input, replacement); return result; } static string Iteration() { int n = 10; string input = "qwertyuiopqqwertyuiopqwertyuiopwertyuio"; for (int i = n; i < input.Length; i += n + 1) { input = input.Insert(i, "\n"); } return input; } 
    • In the regex bug: if the length of the string is a multiple of 10, then a newline will also be added to the end, although in theory it should not. - Qwertiy
    • How to see ... Satisfies the condition) - vusaldev