I tried to mask the characters in a creditcard number string using character \'X\'.I wrote two functions as below .The second function uses commons.lang.StringUtils
Here you go. Clean and reusable:
/**
* Applies the specified mask to the card number.
*
* @param cardNumber The card number in plain format
* @param mask The number mask pattern. Use # to include a digit from the
* card number at that position, use x to skip the digit at that position
*
* @return The masked card number
*/
public static String maskCardNumber(String cardNumber, String mask) {
// format the number
int index = 0;
StringBuilder maskedNumber = new StringBuilder();
for (int i = 0; i < mask.length(); i++) {
char c = mask.charAt(i);
if (c == '#') {
maskedNumber.append(cardNumber.charAt(index));
index++;
} else if (c == 'x') {
maskedNumber.append(c);
index++;
} else {
maskedNumber.append(c);
}
}
// return the masked number
return maskedNumber.toString();
}
Sample Calls:
System.out.println(maskCardNumber("1234123412341234", "xxxx-xxxx-xxxx-####"));
> xxxx-xxxx-xxxx-1234
System.out.println(maskCardNumber("1234123412341234", "##xx-xxxx-xxxx-xx##"));
> 12xx-xxxx-xxxx-xx34
Good luck.
Firstly, if you make measurements of such a short-running code, you often do not get accurate results due to the minimal timing resolution your CPU/library/whatever provides (which means you usually get to see 0ms or the same small value over and over).
Second and more importantly, do not optimize this! "Premature optimization is the root of all evil" and in a case where you have only a few ms that you want to optimize the effort is thoroughly wasted. You would have to mask millions of credit cards before you should even remotely think about optimizing this simple mask method.