Arcane Arcane - 2 months ago 8
Java Question

How to replace a number in comma separated String?

I have a String Like this.

line = "AAL,American Airlines Group,100";


and I want to replace that '100' with another number. Let's say 200. I tried following methods but with no luck.

String[] item = line.split(",");
String replace = "200";
line.replaceAll(item[2],replace);


Tried using
\\\d
and
\\\d+
instead of
item[2]
but it doesn't work. Any help is much appreciated.

Code runs without any errors. But the String "line" doesn't get modified at all.

Answer

Since Strings are immutable, you have to pass it to a new variable or to the current variable:

line = line.replaceAll(item[2],replace);

The both ways with item[2] or \\d+ should work.