Mask Mobile Number Using C#

By | September 30, 2011

A small piece of code which mask any string with specific mask characters.

// Mask the mobile.
// Usage: MaskMobile("13456789876", 3, "****") => "134****9876"
public static string MaskMobile(string mobile, int startIndex, string mask)
{
    if (string.IsNullOrEmpty(mobile))
        return string.Empty;

    string result = mobile;
    int starLengh = mask.Length;


    if (mobile.Length >= startIndex)
    {
        result = mobile.Insert(startIndex, mask);
        if (result.Length >= (startIndex + starLengh * 2))
            result = result.Remove((startIndex + starLengh), starLengh);
        else
            result = result.Remove((startIndex + starLengh), result.Length - (startIndex + starLengh));

    }

    return result;
}

Category: c#