Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Character Replacement in a String in Java

Currently, I have an array of Strings, each with random characters in it that are random in length. I want to replace every "A" with an "X", how would I come about doing this?

Example:

String str = "ABCDEFGAZYXW";

I want the String to become "XBCDEFGXZYXW". I tried to use:

str.replaceAll("A", "X");

But it does not change the string. Any help is greatly appreciated!

like image 551
Raymosrunerx Avatar asked Mar 05 '26 08:03

Raymosrunerx


2 Answers

str = str.replaceAll("A", "X");

The replaceAll method doesn't change the string (strings in Java are immutable) but creates a new String object and returns it as a result of the function call. In this way we change the reference to the new object where the old one is not changed but simply not referenced.

like image 106
Adam Sznajder Avatar answered Mar 07 '26 21:03

Adam Sznajder


Strings in Java are immutable, you're on the right track by using replaceAll(), but you must save the new string returned by the method somewhere, for example in the original string (if you don't mind modifying it). What I mean is:

String str = "ABCDEFGAZYXW";
str = str.replaceAll("A", "X"); // notice the assignment!
like image 43
Óscar López Avatar answered Mar 07 '26 20:03

Óscar López



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!