Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 686
fraxool Avatar asked Jun 08 '15 16:06

fraxool


People also ask

How do you remove the first and last letter of a string in Java?

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.

How do you replace all letters in Java?

replaceAll("[a-zA-Z]","@"); If you want to replace all alphabetical characters from all locales, use the pattern \p{L} .

How do you subtract a letter from a string in Java?

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.

How do you change the last and first letter of a string?

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.


1 Answers

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.

like image 105
anubhava Avatar answered Sep 22 '22 01:09

anubhava