L
L
LiptonOlolo2016-06-06 11:05:21
C++ / C#
LiptonOlolo, 2016-06-06 11:05:21

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

3 answer(s)
A
Anton Fedoryan, 2016-06-06
@LiptonOlolo

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

#
#algooptimize #bottize, 2016-06-06
@user004

Hand add 4 characters to the stringbuilder and possibly regular, possibly linq for perverts.

W
WarFollowsMe, 2016-06-29
@WarFollowsMe

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 question

Ask a Question

731 491 924 answers to any question