Programming Tips - Java: Change all whitespace into underscores in a String

Date: 2014oct19 Update: 2025sep8 Language: java Level: novice Q. Java: Change all whitespace into underscores in a String A. Here is a nice way to clean a string:
String clean(final String s) { return 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. This is something you might want to do to make a file name. Full working example:
class Demo { static String clean(final String s) { return s.trim().replaceAll("\\s+", "_"); } public static void main(String [] args) { String cleanFilename = clean(" This is a filename.jpg "); System.out.println("clean=" + cleanFilename); } }
Output:
clean=This_is_a_filename.jpg