Raymosrunerx
Raymosrunerx

Reputation: 179

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!

Upvotes: 2

Views: 488

Answers (6)

eavom
eavom

Reputation: 1097

Basically replaceAll function will take two parameter, one is string which you want to remove and second one is new string which you want to replace and its return type is String.

It will return you new string after replacement.

Here you are calling that method but not storing its new value in variable. you can replace or print it like this

String string = "My Old String with Old value";
System.out.println(string.replaceAll("Old", "New"));
//Or
string = string.replaceAll("Old", "New");
System.out.println(string);

So in your code you should store it into your string object.

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

Upvotes: 0

Mark Byers
Mark Byers

Reputation: 839134

For just replacing a single character with another you can use replace:

str = str.replace('A', 'X');

As many others have already posted String.replaceAll also works, but you should be aware that the first parameter to this method is a regular expression. If you are not aware of this then it might not work as you expect in all cases:

// Replace '.' with 'X'.
str = str.replaceAll(".", "X"); // Oops! This gives "XXXXXXXXXXXX"

Upvotes: 3

Óscar López
Óscar López

Reputation: 236140

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!

Upvotes: 3

Jan-Philipp Niewerth
Jan-Philipp Niewerth

Reputation: 161

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

Strings are immutable in Java.

Upvotes: 2

Philip Sheard
Philip Sheard

Reputation: 5825

You have to assign the result, viz:

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

Upvotes: 2

Adam Sznajder
Adam Sznajder

Reputation: 9216

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.

Upvotes: 4

Related Questions