Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If you have multiple spaces inside a string in Java, how do you condense them into a single space between words?

Tags:

java

string

If a string has multiple spaces between words:

The    cat         sat            on           the           mat.

How do you make it a single space?

The cat sat on the mat.

I tried this but it didn't work:

myText = myText.trim().replace("  ", " ");
like image 923
Bruce Philby Avatar asked Dec 01 '10 21:12

Bruce Philby


1 Answers

With a regular expression:

myText.trim().replaceAll("\\s+", " ");

This reads: "trim text and then replace all occurrences of one or more than one whitespace character (including tabs, line breaks, etc) by one single whitespace"

See also java.util.regex.Pattern for more details on Java regular expressions:

http://download.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html

like image 70
Lukas Eder Avatar answered Oct 24 '22 19:10

Lukas Eder