Hide email characters:
When email only has one letter then just cover that letter with the
*
symbol e.g.*@gmail.com
When email has two letters then cover second letter with the symbol * e.g.
t*@gmail.com
When email has three letters then cover second and third with the symbol
*
e.g.t**gmail.com
When email has four or more letters then show first three letters and add 4 stars at the ends - e.g.
tim****@gmail.com tom****@gmail.com
My code works but I feel like its way too much hard-coding and can be done much cleaner
public static String hideSomeOfEmailValue(String privateEmail) {
StringBuilder stringBuilder = new StringBuilder(privateEmail);
int atSignIndex = privateEmail.indexOf("@");
String emailName = privateEmail.substring(0, atSignIndex);
if (emailName.length() == 1) {
return stringBuilder.replace(0, emailName.length(), "*").toString();
}
if (emailName.length() > 1 && emailName.length() < 4) {
return stringBuilder.replace(1, atSignIndex, StringUtils.repeat("*", emailName.length() - 1)).toString();
} else {
stringBuilder = new StringBuilder(privateEmail.substring(0, 2));
String emailProvider = privateEmail.substring(atSignIndex);
stringBuilder.append("****").append(emailProvider);
return stringBuilder.toString();
}
- locate at what index at sign located
- trim everything until at sign which gives us name of the email only so we can easily.