I am trying to replace a +
character into a hyphen
I have in my string.
String str = \"word+word\";
str.replaceAll(\'+ \', \'-\');
`replaceAll´ is for regular expressions and strings are immutable. Use:
str = str.replace("+", "-");
instead...
The replaceAll
function takes a regular expression as its first argument. It so happens that +
is a special character in regular expression language. Try replacing +
with \\+
. This will escape the plus sign, thus making the code to treat it like a normal character.
Also, the replaceAll
method yields a string, so that will not work. Try doing:
String str = "word+word";
str = str.replaceAll("\\+ ", "-");
If you are not sure about the escape sequence you need to use,
You could simply do this.
str = str.replaceAll(Pattern.quote("+"), "-");
This will automatically escape the regex predefined tokens to match in a literal way
Use
str = str.replaceAll("\\+", "-");
A few errors in your code :
+
char must be escaped as the first argument is a regular expression (and \
itself must be escaped in java string literals)Just use replace
:
str = str.replace('+', '-');
This one doesn't work on regex but take characters as they are.
Also as you see you have to reassing value again to your str
variable because String
in Java are immutable. In this case method replace
doesn't change current String
(str
) but create new one with replaced +
to '-'.
Use "" as opposed to '' in replaceAll.
String java.lang.String.replaceAll(String regex, String replacement)