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

后端 未结 2 1627
栀梦
栀梦 2021-02-20 18:12

If a string has multiple spaces between words:

The    cat         sat            on           the           mat.

How do you make it a single sp

2条回答
  •  再見小時候
    2021-02-20 18:43

    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.

提交回复
热议问题