Search code examples
c#string-formatting

Format a string in C# (not number or date) to a given pattern


Is there something like string.format for formatting strings where I can pass a the goal pattern. string.format seems to be only for formatting numbers and patterns and inserting values inside a given position. Is there a general solution to formatting strings after a given pattern than programming it out myself?

I want to give the goal pattern and an input string and get out the string in the pattern I’ve provided.

I can give some examples.

Input               Output           Input pattern (idea)
---------------------------------------------------------
123.456.001         00123.456.001    00000.000.###
D1234567            D-123-4567       D-000-#### (where D is literal)

So, my question is: Is there a way to format a string to a given pattern like there is for number and dates?


Solution

  • I would consider making customer formatter classes for each of the different formats you require. There is a very simple example below with no error handling etc...

    // custom formatter class
    public class FormatD : IFormattable
    {
        public string ToString(string format, IFormatProvider provider)
        {
            return format[0] + "-" + format.Substring(1,3) + "-" + format.Substring(4);
        }
    }
    

    To call:

     var input = "D1234567";
     var ouput = String.Format("{0:" + input + "}", new FormatD());