Pooya
is correct in that you should use
inspect = inspect.replaceAll('&', '~');
However I think their answer lags the reasoning behind why this should be done. So the reason why you have to do this is because when you construct a string, in your case the value of inspect
the value of that String is constant and cannot be changed after they are created.
(Unless you are using String buffers that is that support mutable Strings.)
The reason it cannot be changed is because a String Object is in fact immutable.
So what happens when you use inspect.replaceAll('&', '~')
is it will actually be using the the method:
public String replaceAll(String regex, String replacement)
See String Documentation for a full description here.
As per the documentation:
Replaces each substring in this string that matches the given regular expression with the given replacement value.
Eventually this method will return a String value, so it will need to place that String value somewhere when it is returned. So the code you have of inspect.replaceAll('&', '~');
doesn't actually place the new String into an object so inspect remains the same. So as per Pooya
s answer all you need to do is place it into the object again like:
inspect = inspect.replaceAll('&', '~');