Here you can find the source of collapseWhitespace(String s, boolean trim)
public static String collapseWhitespace(String s, boolean trim)
//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; } }