Removes all extra whitespace (multiple spaces or tabs) from a string - Java java.lang

Java examples for java.lang:String New Line

Description

Removes all extra whitespace (multiple spaces or tabs) from a string

Demo Code

/**/*  ww  w .j  a v  a2  s. c  om*/
 * Copyright (c) 2005-2006 Aptana, Inc.
 *
 * 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. If redistributing this code,
 * this entire header must remain intact.
 */
//package com.java2s;

public class Main {
    /**
     * Removes all extra whitespace (multiple spaces or tabs) from a string
     * 
     * @param text
     *            The string to strip of '\n'
     * @return The string minus the whitespace
     */
    public static String stripWhitespace(String text) {
        if (text == null) {
            return null;
        }

        return text.replaceAll("\\s+", " "); //$NON-NLS-1$ //$NON-NLS-2$
    }
}

Related Tutorials