Browse - Programming Tips - How can I change all whitespace into underscores in a String?

Date: 2014oct19
Language: java
Level: beginner

Q.  How can I change all whitespace into underscores in a String?

A.  Here is a nice way to clean a string:

s = s.trim().replaceAll("\\s+", "_");
trim() removes leading and trailing whitespace (tab, space, newline) characters. Then the replaceAll("\\s+","_") converts any run of whitespace into a underscore.