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
  • 51
  • 1
  • 6

2 Answers2

2

String is immutable. You should do something like

example = example.replaceAll(Character.toString('x') , Integer.toString(1));
dejvuth
  • 6,986
  • 3
  • 33
  • 36
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,201
  • 24
  • 48
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97