Java String Whitespace Collapse collapseWhiteSpace(String text)

Here you can find the source of collapseWhiteSpace(String text)

Description

collapse White Space

License

Open Source License

Declaration

public static String collapseWhiteSpace(String text) 

Method Source Code

//package com.java2s;
/*// w ww .  j  av  a2s  . c  o m
 *  PHEX - The pure-java Gnutella-servent.
 *  Copyright (C) 2001 - 2006 Phex Development Group
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 * 
 *  Created on 23.11.2005
 *  --- CVS Information ---
 *  $Id: ParserUtils.java 3362 2006-03-30 22:27:26Z gregork $
 */

public class Main {
    public static String collapseWhiteSpace(String text) {
        int len = text.length();
        int s;
        for (s = 0; s < len; s++)
            if (isWhiteSpace(text.charAt(s)))
                break;

        if (s == len)
            return text;
        StringBuffer result = new StringBuffer(len);
        if (s != 0) {
            for (int i = 0; i < s; i++)
                result.append(text.charAt(i));

            result.append(' ');
        }
        boolean inStripMode = true;
        for (int i = s + 1; i < len; i++) {
            char ch = text.charAt(i);
            boolean b = isWhiteSpace(ch);
            if (!inStripMode || !b) {
                inStripMode = b;
                if (inStripMode)
                    result.append(' ');
                else
                    result.append(ch);
            }
        }

        len = result.length();
        if (len > 0 && result.charAt(len - 1) == ' ')
            result.setLength(len - 1);
        return result.toString();
    }

    private static final boolean isWhiteSpace(char ch) {
        if (ch > ' ')
            return false;
        else
            return ch == '\t' || ch == '\n' || ch == '\r' || ch == ' ';
    }
}

Related

  1. collapseWhitespace(String s, boolean trim)
  2. collapseWhitespace(String str)
  3. collapseWhitespace(String string)
  4. collapseWhiteSpace(String string)
  5. collapseWhitespace(String text)
  6. collapseWhiteSpace(StringBuffer oriText)
  7. collapseWhiteSpaces(String str)