You have
user.nick@domain.com
and 开发者_开发问答result should be:
******@domain.com
Currently I'm doing it this way:
public static String removeUserFromEmail(String email) {
StringBuffer sbEmail = new StringBuffer(email);
int start = sbEmail.indexOf("@");
sbEmail.delete(0, start);
return "******" + sbEmail.toString();
}
Is there something simpler or more elegant?
i would be inclined to run indexOf on email string before putting it in the stringbuffer...
int start = email.indexOf( '@' );
if( start == -1 )
{
// handle invalid e-mail
}
else
{
return "*****" + email.substring( start );
}
Nothing wrong with that solution, although I have two suggestions:
1) Use StringBuilder instead of StringBuffer unless you need to synchronize access between multiple threads. There is a performance penalty associated with StringBuffer that for this application is likely unnecessary.
2) One of the benefits of StringBuilder/Buffer is avoiding excessive string concatenations.
Your return line converts the Buffer to a string, and then concatenates. I would probably do this instead:
int start = email.indexOf("@");
if (start < 0) {
return ""; // pick your poison for the error condition
}
StringBuilder sbEmail = new StringBuilder(email);
sbEmail.replace(0, start, "******");
return sbEmail.toString();
FYI - my solution is really just some thoughts on your current use of StringBuffer (which are hopefully helpful). I would recommend Konstantin's solution for this simple string exercise. Simple, readable, and it gives you the opportunity to handle the error condition.
"some.user@domain.com".replaceAll("^[^@]+", "******");
Looks OK. Better check if indexOf
returns -1
.
public static String removeUserFromEmail(String email) {
String[] pieces = email.split("@");
return (pieces.length > 1 ? "******" + pieces[1] : email);
}
You could use a regex, but your solution seems fine to me. Probably faster than the regex too.
精彩评论