Format string with dashes

Viewed 25636

I have a compressed string value I'm extracting from an import file. I need to format this into a parcel number, which is formatted as follows: ##-##-##-###-###. So therefore, the string "410151000640" should become "41-01-51-000-640". I can do this with the following code:

String.Format("{0:##-##-##-###-###}", Convert.ToInt64("410151000640"));

However, The string may not be all numbers; it could have a letter or two in there, and thus the conversion to the int will fail. Is there a way to do this on a string so every character, regardless of if it is a number or letter, will fit into the format correctly?

6 Answers

Here is a simple extension method with some utility:

    public static string WithMask(this string s, string mask)
    {
        var slen = Math.Min(s.Length, mask.Length);
        var charArray = new char[mask.Length];
        var sPos = s.Length - 1;
        for (var i = mask.Length - 1; i >= 0 && sPos >= 0;)
            if (mask[i] == '#') charArray[i--] = s[sPos--];
            else
                charArray[i] = mask[i--];
        return new string(charArray);
    }

Use it as follows:

        var s = "276000017812008";
        var mask = "###-##-##-##-###-###";
        var dashedS = s.WithMask(mask);

You can use it with any string and any character other than # in the mask will be inserted. The mask will work from right to left. You can tweak it to go the other way if you want.

Have fun.

Related