ExtensionMethod.NET Home of 875 C#, Visual Basic, F# and Javascript extension methods

FormatWithMask

Formats a string with the specified mask

Source

/// <summary>
/// Formats the string according to the specified mask
/// </summary>
/// <param name="input">The input string.</param>
/// <param name="mask">The mask for formatting. Like "A##-##-T-###Z"</param>
/// <returns>The formatted string</returns>
public static string FormatWithMask(this string input, string mask)
{
    if (input.IsNullOrEmpty()) return input;
    var output = string.Empty;
    var index = 0;
    foreach (var m in mask)
    {
        if (m == '#')
        {
            if(index < input.Length)
            {
                output += input[index];
                index++;
            }
        }
        else
            output += m;
    }
    return output;
}

Example

var s = "aaaaaaaabbbbccccddddeeeeeeeeeeee".FormatWithMask("Hello ########-#A###-####-####-############ Oww");
s.ShouldEqual("Hello aaaaaaaa-bAbbb-cccc-dddd-eeeeeeeeeeee Oww");

var s = "abc".FormatWithMask("###-#");
s.ShouldEqual("abc-");

var s = "".FormatWithMask("Hello ########-#A###-####-####-############ Oww");
s.ShouldEqual("");

Author: Vincent van Proosdij

Submitted on: 6 dec 2011

Language: C#

Type: System.String

Views: 21452