Reputation: 1579
I want to insert -
in between them at 4
digits interval in the given string. In the string there will be no special characters and it is a controller code.
string char = "123456789012"
I want answer
string char = "1234-5678-9012"
Upvotes: 1
Views: 827
Reputation: 98750
As a non-regex alternative, you can use Batch
from MoreLINQ
like;
string s = "123456789012";
var list = s.Batch(4, seq => new string(seq.ToArray()));
Console.WriteLine(string.Join("-", list));
Prints
1234-5678-9012
Upvotes: 0
Reputation: 11228
You can use Regex.Replace
(combined with String.Trim
to remove the trailing dash):
string str = "123456789012";
string res = Regex.Replace(str, @"\d{4}", match => match + "-").Trim('-');
Console.WriteLine(res); // 1234-5678-9012
Upvotes: 3