Java 11 and later
str = "*".repeat(str.length());
Note: This replaces newlines \n
with *
. If you want to preserve \n
, see solution below.
Java 10 and earlier
str = str.replaceAll(".", "*");
This preserves newlines.
To replace newlines with *
as well in Java 10 and earlier, you can use:
str = str.replaceAll("(?s).", "*");
The (?s)
doesn’t match anything but activates DOTALL
mode which makes .
also match \n
.