Hello. I have a string with 16 alphanumeric characters, e.g. F4194E7CC775F003. I'd like to format it as F419-4E7C-C775-F003.
I tried using
string.Format("{0:####-####-####-####}","F4194E7CC775F003");
but this doesn't work since it's not a numeric value.
So I came up with the following:
public class DashFormatter : IFormatProvider, ICustomFormatter
{
public object GetFormat(Type formatType)
{
return this;
}
public string Format(string format, object arg, IFormatProvider formatProvider)
{
char[] chars = arg.ToString().ToCharArray();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < chars.Length; i++)
{
if (i > 0 && i % 4 == 0)
{
sb.Append('-');
}
sb.Append(chars[i]);
}
return sb.ToString();
}
}
and by using
string.Format(new DashFormatter(), "{0}", "F4194E7CC775F003");
I was able to solve the problem, however I was hoping there is a better/simpler way to do it? Perhaps some LINQ magic?
Thanks.