Java String Whitespace Collapse collapseWhiteSpaces(String str)

Here you can find the source of collapseWhiteSpaces(String str)

Description

Collapses consecutive white spaces into one space.

License

Open Source License

Declaration

public static String collapseWhiteSpaces(String str) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2007, 2009 Oracle. All rights reserved.
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0, which accompanies this distribution
 * and is available at http://www.eclipse.org/legal/epl-v10.html.
 * //  ww  w.j  ava  2  s  .  co m
 * Contributors:
 *     Oracle - initial API and implementation
 ******************************************************************************/

public class Main {
    /**
     * Collapses consecutive white spaces into one space.
     */
    public static String collapseWhiteSpaces(String str) {
        String result = null;
        if (str != null) {
            StringBuffer buffer = new StringBuffer();
            boolean isInWhiteSpace = false;
            for (int i = 0; i < str.length(); i++) {
                char c = str.charAt(i);
                if (Character.isWhitespace(c)) {
                    isInWhiteSpace = true;
                } else {
                    if (isInWhiteSpace)
                        buffer.append(" ");
                    isInWhiteSpace = false;
                    buffer.append(c);
                }
            }
            result = buffer.toString();
        }
        return result;
    }
}

Related

  1. collapseWhitespace(String string)
  2. collapseWhiteSpace(String string)
  3. collapseWhiteSpace(String text)
  4. collapseWhitespace(String text)
  5. collapseWhiteSpace(StringBuffer oriText)