java 常用方法 normalizeSpace

Remove leading and trailing whitespace and then replacing sequences of whitespace characters.

public static String normalizeSpace(String str) {

}

要求:需要运行速度快

     public static final String EMPTY_STRING = "";
     public static String normalizeSpace(String str) {
        if (null == str) {
            return null;
        }

        if (EMPTY_STRING == str) {
            return EMPTY_STRING;
        }

        int length = str.length();
        int start = 0, end = length;
        while ((str.charAt(start) == ' ' && start < length)) {
            start++;
        }
        if (start == end) {
            return EMPTY_STRING;
        }
        while ((end > start) && str.charAt(end - 1) == ' ') {
            end--;
        };

        if (start == end) {
            return EMPTY_STRING;
        }

        StringBuilder buf = new StringBuilder(end - start);
        boolean sawEmptyChar = false;
        char tempChar = 0;
        for (int i = start; i < end; i++) {
            tempChar = str.charAt(i);
            if (tempChar == ' ') {
                if (!sawEmptyChar) {
                    sawEmptyChar = true;
                    buf.append(' ');
                }
            } else {
                sawEmptyChar = false;
                buf.append(tempChar);
            }
        }
        return buf.toString();
    }