Java String Whitespace Normalize normalizeWhitespaces(String s)

Here you can find the source of normalizeWhitespaces(String s)

Description

Replaces all duplicated whitespace characters with single space.

License

Open Source License

Declaration

public static String normalizeWhitespaces(String s) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2011 Google, Inc./*  ww w.j  a v a2  s .c  o m*/
 * 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
 *
 * Contributors:
 *    Google, Inc. - initial API and implementation
 *******************************************************************************/

public class Main {
    /**
     * Replaces all duplicated whitespace characters with single space.
     */
    public static String normalizeWhitespaces(String s) {
        int length = s.length();
        StringBuffer normalized = new StringBuffer(length);
        //
        boolean needSpace = false;
        for (int index = 0; index < length; index++) {
            char c = s.charAt(index);
            if (Character.isWhitespace(c)) {
                needSpace = true;
            } else {
                if (needSpace) {
                    needSpace = false;
                    normalized.append(' ');
                }
                normalized.append(c);
            }
        }
        // add trailing space
        if (needSpace) {
            normalized.append(' ');
        }
        //
        return normalized.toString();
    }
}

Related

  1. normalizeWhitespace(String orig)
  2. normalizeWhitespace(String s)
  3. normalizeWhitespace(String source)
  4. normalizeWhiteSpace(String src)
  5. normalizeWhitespace(String text)
  6. normalizeWhitespaces(String text)