Remove all occurrences of all specified characters. - Java java.lang

Java examples for java.lang:String Trim

Description

Remove all occurrences of all specified characters.

Demo Code


//package com.java2s;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;

public class Main {
    /**/*ww w .  jav a2s . c o  m*/
     * Remove all occurrences of all specified characters.
     * <p>
     * This is an easy way to e.g. remove all formatting chars such as ' ', '\t', '\n' from Strings for easy comparison
     * of code generated String.
     * 
     * @param baseString
     *            the string to trim
     * @param removeChars
     *            the characters to remove
     * @return a string with the specified characters removed.
     */
    public static String removeAll(final String baseString,
            final Character... removeChars) {
        final StringBuffer resultString = new StringBuffer();
        // cache for quick lookup
        final HashMap<Character, Object> charMatchMap = new HashMap<Character, Object>();
        for (final Character c : removeChars) {
            charMatchMap.put(c, c);
        }

        for (int i = 0; i < baseString.length(); i++) {
            final char c = baseString.charAt(i);
            if (charMatchMap.containsKey(c) == false) {
                resultString.append(c);
            }
        }
        return resultString.toString();
    }
}

Related Tutorials