Removes all extra whitespace characters from the passed String. - Java java.lang

Java examples for java.lang:String Whitespace

Description

Removes all extra whitespace characters from the passed String.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String string = "java2s.com";
        System.out.println(squeeze(string));
    }//from   w  ww .  j  av a 2s. co m

    /**
     * Removes all extra whitespace characters from the passed String. All
     * occurrences of consecutive white space characters as defined by
     * Character#isWhitespace(char) are reduced down to one whitespace character
     * (the first character in the sequence). A new modified String is returned.
     * The string is not trimed.
     * 
     * @param string
     *            the String to modify
     * @return a new String without repeated whitespace characters.
     */
    public static String squeeze(String string) {

        if (string == null) {
            return null;
        }

        char[] oldString = string.toCharArray();
        int oldLength = oldString.length;
        char[] newString = new char[oldLength];
        int newLength = 0;
        char currentChar;
        boolean consecutive = false;

        for (int i = 0; i < oldLength; ++i) {
            currentChar = oldString[i];
            if (Character.isWhitespace(currentChar)) {
                if (!consecutive) {
                    consecutive = true;
                    newString[newLength] = currentChar;
                    newLength++;
                }
            } else {
                consecutive = false;
                newString[newLength] = currentChar;
                newLength++;
            }
        }

        return new String(newString, 0, newLength);
    }
}

Related Tutorials