How to split a string using a dash?

Let's say there is a line:
string @string = "123456789";

The question is: how can I split using " - " every 4 characters? I.e. that the output result was the same: "1234-5678-9"??
July 8th 19 at 16:31
5 answers
July 8th 19 at 16:33
Solution
int step = 4;
string s = "1234567891233";
List<int> insertPosition = new List<int>();
for (int i = 1; i < (s.Length / step) + 1; i++)
{
 insertPosition.Add(step * i);
}

insertPosition.Reverse();

s = insertPosition.Aggregate(s, (current, d) => current.Insert(d, "-"));
Console.WriteLine(s); // 1234-5678-9123-3</int></int>
Thank you :) - Dovie.Schroeder commented on July 8th 19 at 16:36
Terrible decision, direct feel to the PHP approach. Strings in C# are immutable and each operation Insert row creates a new row object, but at the same time large. Again, the excess use of list does not add to the optimality and readability. - florencio.Abernathy commented on July 8th 19 at 16:39
July 8th 19 at 16:35
Solution
public static class Ext
{
 public static IEnumerable<string> Chunk(this string str, int chunkSize)
{
 return Enumerable.Range(0, (int)Math.Ceiling((double)str.Length / chunkSize))
 .Select(i => str.Substring(i * chunkSize, Math.Min(chunkSize, str.Length - (i * chunkSize))));
}

 public static string Join(this IEnumerable<string> src, string delimiter)
{
 return String.Join(delimiter, src);
}
}

public class Test
{
 public static void Main()
{
Console.WriteLine("1234567890".Chunk(3).Join("-"));
}
}</string></string>

Given the laziness of Linq and nizmennosti lines, this solution is clearly optimal, and visually clearer.
Thank you)) - Dovie.Schroeder commented on July 8th 19 at 16:38
July 8th 19 at 16:37
Solution
string str = "123456789";
 System.Text.StringBuilder result = new System.Text.StringBuilder();
 for(int i = 0; i < str.Length; i++)
 result.Append(i % 4 == 0 && i > 0? $"-{str[i]}" : $"{str[i]}");
 Console.WriteLine($"{result}");

If a couple of gigs to process characters using string instead of StringBuilder, it will be very visible lack of resources.
July 8th 19 at 16:39
Hands to add 4 icons in StringBuilder and perhaps regular , perhaps linqом for perverts.
July 8th 19 at 16:41
strange that there was no example with the regular season. In my opinion this solution is more concise
var some = "123456789";
var result = Regex.Replace(some, "([0-9]{4})", "$1-");
if you need any text, then here it is:
Regex.Replace(some, "(.{4})", "$1-");

Find more questions by tags C#