Java String Whitespace Collapse collapseWhitespace(String s)

Here you can find the source of collapseWhitespace(String s)

Description

Collapse continuous whitespace into one single " ".

License

Open Source License

Parameter

Parameter Description
s operate on this string

Return

result with collapsed whitespace

Declaration

static public String collapseWhitespace(String s) 

Method Source Code

//package com.java2s;

public class Main {
    /**/*w  w w.j  a  va 2 s  .  c  o  m*/
     * Collapse continuous whitespace into one single " ".
     *
     * @param s operate on this string
     * @return result with collapsed whitespace
     */
    static public String collapseWhitespace(String s) {
        int len = s.length();
        StringBuilder b = new StringBuilder(len);
        for (int i = 0; i < len; i++) {
            char c = s.charAt(i);
            if (!Character.isWhitespace(c)) {
                b.append(c);
            } else {
                b.append(' ');
                while ((i + 1 < len) && Character.isWhitespace(s.charAt(i + 1))) {
                    i++; /// skip further whitespace
                }
            }
        }
        return b.toString();
    }
}

Related

  1. collapseSpaces(String text, char[] spaceCharacters)
  2. collapseWhiteSpace(CharSequence value)
  3. collapseWhiteSpace(final String s)
  4. collapseWhiteSpace(String content)
  5. collapseWhitespace(String in, char replacementChar)
  6. collapseWhitespace(String s, boolean trim)
  7. collapseWhitespace(String str)
  8. collapseWhitespace(String string)
  9. collapseWhiteSpace(String string)