Java String Whitespace Collapse collapseSpaces(String text, char[] spaceCharacters)

Here you can find the source of collapseSpaces(String text, char[] spaceCharacters)

Description

Collapses spaces in the text, but does not trim the resulting string.

License

Apache License

Parameter

Parameter Description
text a parameter
spaceCharacters array of characters treated as spaces

Declaration

public static String collapseSpaces(String text, char[] spaceCharacters) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

public class Main {
    /**/*from  www.  ja va 2 s.co m*/
     * Collapses spaces in the text, but does not trim the resulting string.
     *
     * @param text
     * @param spaceCharacters array of characters treated as spaces
     * @return
     */
    public static String collapseSpaces(String text, char[] spaceCharacters) {
        if (text == null || text.length() == 0)
            return text;

        StringBuffer result = new StringBuffer();
        char[] textChars = text.toCharArray();

        boolean wasSpace = false;
        for (int i = 0; i < textChars.length; i++) {
            if (!isCharacterInArray(textChars[i], spaceCharacters)) {
                result.append(textChars[i]);
                wasSpace = false;
            } else if (!wasSpace) {
                result.append(' ');
                wasSpace = true;
            }
        }

        return result.toString();
    }

    private static boolean isCharacterInArray(char c, char[] characters) {
        for (int i = 0; i < characters.length; i++) {
            if (c == characters[i])
                return true;
        }

        return false;
    }
}

Related

  1. collapseSpaces(String argStr)
  2. collapseSpaces(String s)
  3. collapseWhiteSpace(CharSequence value)
  4. collapseWhiteSpace(final String s)
  5. collapseWhiteSpace(String content)
  6. collapseWhitespace(String in, char replacementChar)