I have a string, for example this one:
stackoverflow
And I would like to get the following output in Java (Android):
s***********w
So we keep the first and the last letters but the other ones are replaced by this sign "*". I want the length of the string to be the same from the input to the output.
Here is the code of the function I have now.
String transform_username(String username)
{
// Get the length of the username
int username_length = username.length();
String first_letter = username.substring(0, 1);
String last_letter = username.substring(username_length - 1);
String new_string = "";
return new_string;
}
I am able to get the first and the last letter, but I don't really know how to put the "*" in the middle of the word. I know I could loop over it, but it's obviously not a good solution.
The idea is to use the deleteCharAt() method of StringBuilder class to remove first and the last character of a string. The deleteCharAt() method accepts a parameter as an index of the character you want to remove.
replaceAll("[a-zA-Z]","@"); If you want to replace all alphabetical characters from all locales, use the pattern \p{L} .
Use the deleteCharAt Method to Remove a Character From String in Java. The deleteCharAt() method is a member method of the StringBuilder class that can also be used to remove a character from a string in Java.
You have 2 solutions : 1) convert the String to a char array then switch the chars and rebuild the String. Or 2) concatene last character + middle substring + 1st character.
In one line regex you can do:
String str = "stackoverflow";
String repl = str.replaceAll("\\B\\w\\B", "*");
//=> s***********w
RegEx Demo
\B
is zero-width assertion that matches positions where \b
doesn't match. That means it matches every letter except first and last.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With