Here you can find the source of collapseWhiteSpaces(String str)
public static String collapseWhiteSpaces(String str)
//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; } }