How to mask part of a string
Short answer
Keep the last characters visible and replace the rest with asterisks using repeat():
void main() {
String card = "4000123456789010";
String masked = "*".repeat(card.length() - 4) + card.substring(card.length() - 4);
IO.println(masked);
}Output:
************9010A general method
A method with "how many to keep at the start and at the end" parameters:
String mask(String text, int keepStart, int keepEnd) {
if (text.length() <= keepStart + keepEnd) {
return text;
}
int hidden = text.length() - keepStart - keepEnd;
return text.substring(0, keepStart) + "*".repeat(hidden) + text.substring(text.length() - keepEnd);
}
void main() {
IO.println(mask("+49 151 2345 6789", 3, 4));
IO.println(mask("abc", 2, 2));
}Output:
+49**********6789
abcIn an email address you usually hide the middle of the name before the @:
void main() {
String email = "anna.smith@example.com";
int at = email.indexOf('@');
String name = email.substring(0, at);
IO.println(name.charAt(0) + "*".repeat(name.length() - 2) + name.charAt(name.length() - 1) + email.substring(at));
}Output:
a********h@example.comCommon mistake
Not checking the length. If the string is shorter than the number of visible characters, repeat() gets a negative number:
void main() {
String code = "12";
IO.println("*".repeat(code.length() - 4) + code);
}Output:
Exception in thread "main" java.lang.IllegalArgumentException: count is negative: -2Functions used in this recipe
- String.repeat() — Repeats a string the given number of times.
- String.substring() — Returns the part of a string between two indexes.
- String.length() — Returns the number of characters in a string.