How to append Hyphens to a string at each nth position?
.net, asp.net, c#
Solution
You could use a little bit of Linq, like this:
string Hyphenate(string str, int pos) {
return String.Join("-",
str.Select((c, i) => new { c, i })
.GroupBy(x => x.i / pos)
.Select(g => String.Join("", g.Select(x => x.c))));
}
Or like this:
string Hyphenate(string str, int pos) {
return String.Join("-",
Enumerable.Range(0, (str.Length - 1) / pos + 1)
.Select(i => str.Substring(i * pos, Math.Min(str.Length - i * pos, pos))));
}
Or you could use a regular expression, like this:
string Hyphenate(string str, int pos) {
return String.Join("-", Regex.Split(str, @"(.{" + pos + "})")
.Where(s => s.Length > 0));
}
Or like this:
string Hyphenate(string str, int pos) {
return String.Join("-", Regex.Split(str, @"(?<=\G.{" + pos + "})(?!$)"));
}
All of these methods will return the same result:
Console.WriteLine(Hyphenate("abcdxy123z", 2)); // ab-cd-xy-12-3z
Console.WriteLine(Hyphenate("abcdxy123z", 3)); // abc-dxy-123-z
Console.WriteLine(Hyphenate("abcdxy123z", 4)); // abcd-xy12-3z
Problem
I am getting strings like `"123456"`, `"abcdef"`, `"123abc"` from another application. I need to format the strings like `"123-456","abc-def"`, `"123-abc"`. The length of the strings can also vary like we can have a string of lenght 30 char. If the 3rd position is chosen then after every 3rd character a hyphen should be inserted. ex: input "abcdxy123z" output "abc-dxy-123-z" for 3rd position. if we choose 2nd position then output will be "ab-cd-xy-12-3z" I tried with String.Format("{0:####-####-####-####}", Convert.ToInt64("1234567891234567")) but if I get a alphanumeric string, it does not work.