You are developing a banking module. You have developed a class named ccMask that has a maskcc method.

Given the code fragment:

class CCMask {

    public static String maskCC(String creditCard) {
        String x = "XXXX-XXXX-XXXX-";
        //line n1
    }

    public static void main(String[] args) {
        System.out.println(maskCC("1234-5678-9101-1121"));
    }
}

You must ensure that the maskcc method returns a string that hides all digits of the credit card number except the four last digits (and the hyphens that separate each group of four digits).

Which two code fragments should you use at line n1, independently, to achieve this requirement?

A.

StringBuilder sb = new StringBuilder(creditCard);
sb.substring(15, 19);
return x + sb;
B.
return x + creditCard.substring(15, 19);
C.
StringBuilder sb = new StringBuilder(x);
sb.append(creditCard, 15, 19);
return sb.toString();
D.
StringBuilder sb = new StringBuilder(creditCard);
StringBuilder s = sb.insert(0, x);
return s.toString();

题解

选项 A 使用到 StringBuilder 对象的「substring」方法,看似可以,但「substring」方法是直接回传新的子字符串,实际上并不会改变 StringBuilder 对象本身的内容。因此这样做没有办法输出我们想要的结果。

选项 B 解决了选项 A 的问题。

选项 C 使用了 StringBuilder 对象来串接出我们想要的结果。

选项 D 是直接在原本的 creditCard 变量所保存的字符串前直接插入「XXXX-XXXX-XXXX-」,这样做不是我们想要的结果。