user1102901
user1102901

Reputation: 565

Java String to one type of character

Is it possible to replace an entire string with one type of character? Is there a method that will do this? One line of course.

Example:

"1234567890" turns to "xxxxxxxxxx"

Upvotes: 1

Views: 133

Answers (3)

trutheality
trutheality

Reputation: 23465

A slightly more lightweight solution than the replaceAll one:

char[] chars = new char[origString.length()];
Arrays.fill(chars,'x');
String newString = new String(chars);

Oh, sorry, you wanted one line:

char[] chars = new char[origString.length()]; Arrays.fill(chars,'x'); String newString = new String(chars);

Upvotes: 6

amit
amit

Reputation: 178451

Is it possible to replace an entire string with one type of character?

No, String is immutable and thus cannot be changed 1, and thus you cannot "1234567890" cannot be turned into "xxxxxxxxxx"

You can create a new String object, which is replaced, as suggested by @BinyaminSharet


(1) Technically, one can change immutable objects using reflection - but it should be avoided at all cost.

Upvotes: 3

MByD
MByD

Reputation: 137342

You can use replaceAll:

String newString = origString.replaceAll(".", "x");

For example, this:

System.out.println("hello".replaceAll(".", "*"));

outputs:

*****

Upvotes: 10

Related Questions