I recently needed to mask out some characters of a credit card string so that only the last 4 were displayed. Surprisingly there doesn’t seem to be many good examples of this so I decided to put together something myself and I figured it would be more useful as an extension method.

public static class StringExtensions
{
	public static string Mask(this string source, int start, int maskLength)
	{
		return source.Mask(start, maskLength, 'X');
	}

	public static string Mask(this string source, int start, int maskLength, char maskCharacter)
	{
		if (start > source.Length -1)
		{
			throw new ArgumentException("Start position is greater than string length");
		}

		if (maskLength > source.Length)
		{
			throw new ArgumentException("Mask length is greater than string length");
		}

		if (start + maskLength > source.Length)
		{
			throw new ArgumentException("Start position and mask length imply more characters than are present");
		}

		string mask = new string(maskCharacter, maskLength);
		string unMaskStart = source.Substring(0, start);
		string unMaskEnd = source.Substring(start + maskLength, source.Length - maskLength);

		return unMaskStart + mask + unMaskEnd;
	}
}
public static class IntegerExtensions
{
	public static string ToStringMask(this int source, int start, int maskLength)
	{
		return source.ToString().Mask(start, maskLength, 'X');
	}

	public static string ToStringMask(this int source, int start, int maskLength, char maskCharacter)
	{
		return source.ToString().Mask(start, maskLength, maskCharacter);
	}
}

The below code will output a string with the first 12 characters replaced with “X”s.

string creditCard = "1234567891234567";
string maskedCreditCard = creditCard.Mask(0, 12);
Categories: Programming

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *