I am thinking about using String.replaceAll()
to remove certain characters in my string. It is unclear which characters are going to be removed (i.e. which characters I want to remove), but I would assume that any character is valid (like [a-zA-Z]
and things like $%!
, etc).
I came across http://www.java-tips.org/java-se-tips/java.lang/strip-certain-characters-from-a-string.html but surely there is a better way than iterating over each character...
Any thoughts on this?
Thanks
EXAMPLE:
Just to clarify, I will have strings of varying lengths. I want to strip characters from it, the exact ones to be determined at runtime, and return the resulting string.
Taking the paragraph above and allowing me to strip out the ",.
", I would return the string:
Just to clarify I will have strings of varying lengths I want to strip characters from it the exact ones to be determined at runtime and return the resulting string
As an aside, I know that replaceAll() uses regular expressions, so if I wanted to strip out the characters "$,.", I would need to escape them too, right?
You can also remove a specified character or substring from a string by calling the String. Replace(String, String) method and specifying an empty string (String. Empty) as the replacement. The following example removes all commas from a string.
You can remove a character from a Python string using replace() or translate(). Both these methods replace a character or string with a given value. If an empty string is specified, the character or string you select is removed from the string without a replacement.
You might want to start by specifying which character you WANT to keep, try something like:
"mystring".replaceAll("[^a-zA-Z]", "")
To only keep letters.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With