Answer the question
In order to leave comments, you need to log in
How to split a string with a dash?
Let's say there is a string: The string @string = "123456789";
question is: how can a string be separated by "-", every 4 characters? That is, so that the output result is: "1234-5678-9"??
Answer the question
In order to leave comments, you need to log in
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
Hand add 4 characters to the stringbuilder and possibly regular, possibly linq for perverts.
It is strange that there was no example with a regular expression. 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 like this:Regex.Replace(some, "(.{4})", "$1-");
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question