简体   繁体   中英

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

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("  ", " ");

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

All you need:

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

Accordigng to specs of replaceAll method of class String : http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replaceAll(java.lang.String,%20java.lang.String)

and specs of Pattern class in java(try to ctrl-F for "whitespace", and "++" ): http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html

In my opinion it's much better to open those pages and take a look by yourself, then just to copy snippet.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM