Drill

ProblemsJava › payments

Mask a card number

easypaymentsStringsJava

Support staff can see the last four digits of a card and nothing else.

maskCard(cardNo: string) → string

Java needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

String maskCard(String cardNo) {
    
}

Worked examples

CallResult
maskCard("4506349012345678")"************5678"
maskCard("12345")"*2345"
maskCard("1234")"1234"
maskCard("")""

Hint

Build the asterisks from the length, then glue on the tail.

Reference solution in Java
String maskCard(String cardNo) {
    if (cardNo.length() <= 4) return cardNo;
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < cardNo.length() - 4; i++) sb.append('*');
    return sb + cardNo.substring(cardNo.length() - 4);
}

The same problem in another language

More payments problems in Java