Search code examples
credit-cardmasking

How to mask first two letter and last four letters of credit card number


How to mask first two letter and last four letters of credit card number. I am able to do the last four digits but the first two digits I can't.

I am using following code:

string result = s.Substring(s.Length - 4).PadLeft(4, '*');

Please let me know the best practice.


Solution

  • You need to cut the text in the string after the first two characters and up to the last four, and then put two asterisks in front and four at the end.

    Substring() is an excellent string function for this, combinef with knowing the length of the string, which Length will give you. Thus, a working code snippet would be:

    var middle = s.Substring(2, s.Length - 2 - 4);
    var result = string.Format("**{0}****", middle);