0

I want to replace a character in string with the replace all method, but this method gives me still the same string.

String example = "5x";
example.replaceAll(Character.toString('x') , Integer.toString(1));

What is wrong with the code?

fjoralba
  • 41
  • 1
  • 6

2 Answers2

2

String is immutable. You should do something like

example = example.replaceAll(Character.toString('x') , Integer.toString(1));
dejvuth
  • 6,726
  • 3
  • 31
  • 35
0

Strings are immutable, meaning they can not be changed.

This can be done simply like this:

String example = "5x";
example = example.replaceAll("x", Integer.toString(1));

You are missing assigning the new string to example.

Zac
  • 2,193
  • 21
  • 47
ΦXocę 웃 Пepeúpa ツ
  • 45,713
  • 17
  • 64
  • 91