快速过滤字符串内容

public class StringFilterHelper {
    private int maxLength;
    private HashMap<String, String> filterStrs = new HashMap<String, String>();

    /**
     * * 初始化需要过滤掉*的数量
     */
    private String initStr(int n) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < n; i++) {
            sb.append('*');
        }
        return sb.toString();
    }

    /**
     * * str-被过滤得字符串 * s-需要过滤得字符串 * 获得剩下未过滤的字符串
     */
    private String getNextStr(String str, int start, int slength) {
        if (start == 0) {
            str = str.substring(slength);
        } else if (start + slength < str.length()) {
            str = str.substring(start + slength);
        }
        return str;
    }

    /**
     * * str-被过滤得字符串 * s-需要过滤得字符串 * 获得过滤后的字符串
     */
    private StringBuffer getFilterStr(StringBuffer sb, String str, int start,
            String s) {
        if (start != 0) {
            sb.append(str.substring(0, start));
        }
        sb.append(filterStrs.get(s));
        return sb;
    }

    /**
     * * str-被过滤的字符串 * 过滤,并组合过滤后的字符串
     */
    public String filter(String str) {
        StringBuffer resultStr = new StringBuffer();
        for (int start = 0; start < str.length(); start++) {
            for (int end = start + 1; end <= str.length()
                    && end <= start + maxLength; end++) {
                String s = str.substring(start, end);
                int slength = s.length();
                if (filterStrs.containsKey(s)) {
                    resultStr = getFilterStr(resultStr, str, start, s);
                    str = getNextStr(str, start, slength);
                    start = 0;
                    end = start;
                }
            }
        }
        resultStr.append(str);
        return resultStr.toString();
    }

    public void put(String key) {
        int keyLength = key.length();
        filterStrs.put(key, initStr(keyLength));
        if (keyLength > this.maxLength)
            maxLength = keyLength;
    }
    
    /**
     *  过滤字符串
     *  @Description    : 主要是过贴子内容
     *  @Method_Name    : filterString
     *  @param filterRole
     *  @param filterStr
     *  @return 
     *  @return         : String
     *  @Creation Date  : Apr 19, 2013 4:10:20 PM 
     *  @version        : v1.00
     *  @Author         : bluesky
     *  @Update Date    : 
     *  @Update Author  : bluesky 
     */
    public static String filterString(String filterRole,String filterStr){
        StringFilterHelper t = new StringFilterHelper();
        String[] s=filterRole.split(",");
        for(int i=0;i<s.length;i++){
            t.put(s[i]);
        }
        return t.filter(filterStr);
    }

    public static void main(String[] agrs) {
        String filterRole="TMD,TNND,操,";
        System.out.println(StringFilterHelper.filterString(filterRole, "TMD,操,TNND.操..TMDTMDTMDTMD.tTNND.操TMDTNNDTNNDTNND操"));
    }

}
posted @ 2013-04-19 16:20  天纯蓝  阅读(605)  评论(0编辑  收藏  举报