Java String Whitespace Collapse collapseWhitespace(String s, boolean trim)

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

Description

collapse Whitespace

License

Apache License

Declaration

public static String collapseWhitespace(String s, boolean trim) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

public class Main {
    private static final char ZERO_WIDTH_SPACE = 0x200B;

    public static String collapseWhitespace(String s, boolean trim) {
        char chars[] = new char[s.length()];
        s.getChars(0, chars.length, chars, 0);

        int r = 0;
        int w = 0;
        while (r < chars.length) {
            char c = chars[r++];

            if (isCollapsibleSpace(c)) {
                int collapseLength = 1;

                //Skip any future characters if they're whitespace
                while (r < chars.length && isCollapsibleSpace(chars[r])) {
                    r++;/* w  w w .  ja  va 2 s.co m*/
                    collapseLength++;
                }

                if (w == 0 && trim) {
                    continue; //Starts with space
                } else if (r >= chars.length && trim) {
                    continue; //Ends with space
                }

                // Replace with ' ', unless the whitespace sequence consists of a single zero width space
                if (collapseLength > 1 || c != ZERO_WIDTH_SPACE) {
                    c = ' ';
                }
            }

            chars[w++] = c;
        }

        return new String(chars, 0, w);
    }

    public static boolean isCollapsibleSpace(char c) {
        return c == ' ' || c == '\t' || c == '\f' || c == ZERO_WIDTH_SPACE;
    }
}

Related

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