anonymous anonymous - 15 days ago 5
Java Question

How to replace all characters in a Java string with stars

I want to replace all the characters in a Java String with

*
character. So it shouldn't matter what character it is, it should be replaced with a
*
.

I know there are heaps of examples there on internet but have not one that replaces every character and I have tried myself but no success.

Answer
str = str.replaceAll(".", "*");

Note: This will not replace line breaks (\n) with *. To do this, you'll need to use

str = str.replaceAll("(?s).", "*");

The (?s) doesn't match anything but activates DOTALL mode which makes . also match \n.

Comments