Dave's Brain

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.

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.