Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String: How to replace multiple possible characters with a single character?

Tags:

java

string

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...

like image 790
ycomp Avatar asked Feb 15 '12 14:02

ycomp


People also ask

How do I replace multiple characters in a string?

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.

How do you replace multiple occurrences of a string in Java?

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.

How do you replace a specific character in a 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.


1 Answers

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.

like image 132
beny23 Avatar answered Sep 25 '22 11:09

beny23