Replace all letters of the string minus the first and last in Java

I have a line like this one:

stackoverflow 

And I would like to get the following output in Java (Android):

 s***********w 

Thus, we save the first and last letters, while others are replaced with this "*" sign. I want the string length to be the same from input to output.

Here is the code of the function that I have.

 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 can get the first and last letter, but I really do not know how to put "*" in the middle of the word. I know that I could iterate over it, but this is obviously not a good solution.

+6
source share
5 answers

In one regex, you can:

 String str = "stackoverflow"; String repl = str.replaceAll("\\B\\w\\B", "*"); //=> s***********w 

RegEx Demo

\B is a zero-width statement that matches positions in which \B does not match. This means that it matches every letter except the first and last.

+10
source
 char[] charArr = username.toCharArray(); for (int i=1;i<charArr.length - 1;i++) { charArr[i] = 'x'; } username = new String(charArr); 
+2
source

If the string may also contain a punctuation attempt:

 str = str.replaceAll("(?!^).(?!$)","*"); 

the images ensure that you do not start or finish ( regex101 demo ).

+2
source

Try

 String ast = "*"; String new_string = first_letter + StringUtils.repeat(ast, username_length-2) + last_letter; 
+1
source

Get the first and last letters in two string variables and '*' in the var string. and a loop from 1 to length-2 and add * to the variable. Then finally add all three.

0
source

All Articles