Java String replace whitespace unicode characters with ' '

Description

Java String replace whitespace unicode characters with ' '


//package com.demo2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        String str = "&^&^$^(&*demo2s.com";
        System.out.println(collapseWhitespace(str));
    }//from  w  ww .  ja va 2s.c  o m

    public static final String WHITE_SPACES = " \r\n\t\u3000\u00A0\u2007\u202F";

    /**
     * Replaces any string of adjacent whitespace characters with the whitespace
     * character " ".
     *
     * @param str the string you want to munge
     * @return String with no more excessive whitespace!
     *
     * @see collapse
     */
    public static String collapseWhitespace(String str) {
        return collapse(str, WHITE_SPACES, " ");
    }

    /**
     * Replaces any string of matched characters with the supplied string.<p>
     *
     * This is a more general version of collapseWhitespace.
     *
     * <pre>
     *   E.g. collapse("hello     world", " ", "::")
     *   will return the following string: "hello::world"
     * </pre>
     *
     * @param str the string you want to munge
     * @param chars all of the characters to be considered for munge
     * @param replacement the replacement string
     * @return String munged and replaced string.
     */
    public static String collapse(String str, String chars, String replacement) {
        if (str == null) {
            return null;
        }

        StringBuilder newStr = new StringBuilder();

        boolean prevCharMatched = false;
        char c;
        for (int i = 0; i < str.length(); i++) {
            c = str.charAt(i);
            if (chars.indexOf(c) != -1) {
                // this character is matched
                if (prevCharMatched) {
                    // apparently a string of matched chars, so don't append anything
                    // to the string
                    continue;
                }
                prevCharMatched = true;
                newStr.append(replacement);
            } else {
                prevCharMatched = false;
                newStr.append(c);
            }
        }

        return newStr.toString();
    }

}



PreviousNext

Related