If there are multiple spaces in a string in Java, how do you group 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 space?

The cat sat on the mat.

I tried this but didn't work:

myText = myText.trim().replace("  "," ");

Solution

Use regular expression:

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

This will be displayed as: "trim the text, and then replace all occurrences of one or more space characters (including tabs, line breaks, etc.) with a single space"

For more details on Java regular expressions, see Java util. regex. Pattern:

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

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>