Perecli Manole said:
I want to convert a string "1234123412341234" to "1234-1234-1234-1234".
This does not work:
String.Format("{0:xxxx-xxxx-xxxx-xxxx}",s)
What will? Although I know there are many other solutions, I am only
interested in ones that use the new braket {0:} style formating because many
web controls require this.
You can supply a custom formatter to accomplish this. String.Format takes an
optional IFormatProvider first parameter. It passes typeof(ICustomFormatter)
to the GetFormat method of this object to see if the format provider
provides a custom formatter. If so, it calls that custom formatter to let it
handle the formatting of the argument.
Here's an example of an IFormatProvider and an ICustomFormatter combined
into one reusable class. It recognizes 'x' characters in the formatting
string as placeholders for characters in the string argument.
public sealed class CustomFormatter: IFormatProvider, ICustomFormatter
{
public static readonly CustomFormatter Instance = new CustomFormatter();
private CustomFormatter() {}
public object GetFormat(Type formatType)
{
return formatType == typeof(ICustomFormatter) ? this : null;
}
public string Format(string format, object arg, IFormatProvider
formatProvider)
{
if (format == null)
return String.Format(formatProvider, "{0}", arg);
string s = arg.ToString();
char[] template = format.ToCharArray();
int j = 0;
for (int i=0; i<template.Length; i++)
if (template
== 'x')
template = (j >= s.Length ? ' ' : s[j++]);
return new string(template);
}
}
To use this custom formatter in your example, you would do this:
string a = "1234123412341234";
string b = String.Format(CustomFormatter.Instance,
"{0:xxxx-xxxx-xxxx-xxxx}", a);