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!
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With