I would like to replace all '.'
and ' '
with a '_'
but I don't like my code...
is there a more efficient way to do this than:
String new_s = s.toLowerCase().replaceAll(" ", "_").replaceAll(".","_");
?
toLowerCase() just there because I want it lower-cased as well...
If you want to replace multiple characters you can call the String. prototype. replace() with the replacement argument being a function that gets called for each match. All you need is an object representing the character mapping which you will use in that function.
You can replace all occurrence of a single character, or a substring of a given String in Java using the replaceAll() method of java. lang. String class. This method also allows you to specify the target substring using the regular expression, which means you can use this to remove all white space from String.
Using 'str.replace() , we can replace a specific character. If we want to remove that specific character, replace that character with an empty string. The str. replace() method will replace all occurrences of the specific character mentioned.
String new_s = s.toLowerCase().replaceAll("[ .]", "_");
EDIT:
replaceAll
is using regular expressions, and using .
inside a character class [ ]
just recognises a .
rather than any character.
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