Reputation: 1632
I've been trying to remove a specific character from an Array of Strings but continue to fail. The char is "$", I don't know what I'm doing wrong so hoping someone would be able to point to the right direction, my code:
for (int y = 0; y<possibleAnswers.length;y++) {
display = possibleAnswers[y].replaceAll("$", "");
System.out.println(display);
}
possibleAnswers contains 4 Strings, one of the 4 has a "$", I want to remove it before displaying it.
When I run the above code, the "$" is displayed, any ideas?
Upvotes: 0
Views: 110
Reputation: 1632
for (int y = 0; y < possibleAnswers.length; y++) {
display = possibleAnswers[y].replace("$", "");
System.out.println(display);
}
As suggested, I used replace method instead of replaceAll and it did the job. At the same time I learned to look at documentation for deeper understanding of such methods.
Thanks for all the help guys, truly appreciated.
Upvotes: 0
Reputation: 140407
The problem with your code is that replaceAll()
expects a "regular expression". The $ character has a specific meaning when used in a regular expression. Therefore you have two options:
replaceAll()
; then you have to "escape the special character"; by using replaceAll("\\$", "")
, or "[$]" as others have pointed out.replace()
that doesn't expect a "regular expression pattern string".Upvotes: 3
Reputation: 204
Just use possibleAnswers[y].replace("$", ""); to remove "$" from string.
Upvotes: 1
Reputation: 7919
Try
possibleAnswers[y].replaceAll("\\$", "");
escape the character because $
is a special character in regular expression and since replaceAll()
take regular expression the string you passed is unidentified.
You can also use replace()
which take string
possibleAnswers[y].replace("$", "");
Upvotes: 1
Reputation: 1163
replaceAll()
accepts a regex, not just a character. When you say "$", you're not telling it to match the '$' character, but to match the ending position of the String or before a newline before the end of the String.
You need to escape the '$', so it knows to match just the character, and not treat it like it's special regex meaning.
Do this like: possibleAnswers[y].replaceAll("\\$", "");
Upvotes: 2
Reputation: 3509
IN your code the $
is keyword
in regex
for matching end of line
i.e. $. SO you will have to escape
it as below.
display = possibleAnswers[y].replaceAll("\\$", "");
Upvotes: 1