masking a creditcard number in java

前端 未结 2 1110
北海茫月
北海茫月 2021-02-08 16:57

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

2条回答
  •  离开以前
    2021-02-08 17:16

    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.

提交回复
热议问题