string @string = "123456789";
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>
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>
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}");
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#