StringUtil.java常用字符操作类

package util;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Array;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * Utility class that allows for easy string manipulation.  This class will be
 * deprecated once the support for JDK 1.3 will no longer be given, as the
 * functionality delivered by this class is incorporated out-of-the box in
 * Java 1.4 (String class, replace methods, etc ...)
 *
 * $Id: StringUtil.java,v 1.3 2003/05/02 17:36:59 vanrogu Exp $
 *
 * @author G黱ther Van Roey ( gunther@javacoding.net )
 */
public class StringUtil {

    /**
     * Replaces the occurences of a certain pattern in a string with a replacement
     * String.
     * @param string the string to be inspected
     * @param pattern the string pattern to be replaced
     * @param replacement the string that should go where the pattern was
     * @return the string with the replacements done
     */
    public static String replace ( String string, String pattern, String replacement ) {
        String replaced = null;

        if (string == null) {
            replaced = null;
        } else if (pattern == null || pattern.length() == 0 ) {
            replaced = string;
        } else {

            StringBuffer sb = new StringBuffer();

            int lastIndex = 0;
            int index = string.indexOf(pattern);
            while (index >= 0) {
                sb.append(string.substring(lastIndex, index));
                sb.append(replacement);
                lastIndex = index + pattern.length();
                index = string.indexOf(pattern, lastIndex);
            }
            sb.append(string.substring(lastIndex));
            replaced = sb.toString();
        }
        return replaced;
    }

    /**
     * @todo add Junit tests for this one
     */
    public static String replace  ( String string, String pattern, String replacement, int start ) {
        String begin = string.substring(0, start);
        String end = string.substring(start);
        return begin + replace(end, pattern, replacement );
    }
    /**
     * 将普通字符串格式化成数据库认可的字符串格式
     *
     * @param input
     *            要格式化的字符串
     * @return 合法的数据库字符串
     */
//    public static String toSql(String input) {
//        if (isEmpty(input)) {
//            return "";
//        } else {
//            return input.replaceAll("\"","'&char(34)&'").replaceAll("'", "'&char(39)&'").replaceAll("  ", "");
//        }
//    }
    public static String toSql(String input) {
        if (isEmpty(input)) {
            return "";
        } else {
            return input.replaceAll("'","''").replaceAll("  ","").replace("  ", "");
        }
    }
    public static String outSql(String input) {
        if (isEmpty(input)) {
            return "";
        } else {
            return input.replaceAll("''", "'");
        }
    }
    /**
     * 截取字符串左侧指定长度的字符串
     *
     * @param input
     *            输入字符串
     * @param count
     *            截取长度
     * @return 截取字符串
     */
    public static String left(String input, int count) {
        if (isEmpty(input)) {
            return "";
        }
        count = (count > input.length()) ? input.length() : count;
        return input.substring(0, count);
    }

    /**
     * 截取字符串右侧指定长度的字符串
     *
     * @param input
     *            输入字符串
     * @param count
     *            截取长度
     * @return 截取字符串
     */
    public static String right(String input, int count) {
        if (isEmpty(input)) {
            return "";
        }
        count = (count > input.length()) ? input.length() : count;
        return input.substring(input.length() - count, input.length());
    }

    /**
     * 从指定位置开始截取指定长度的字符串
     *
     * @param input
     *            输入字符串
     * @param index
     *            截取位置,左侧第一个字符索引值是1
     * @param count
     *            截取长度
     * @return 截取字符串
     */
    public static String middle(String input, int index, int count) {
        if (isEmpty(input)) {
            return "";
        }
        count = (count > input.length() - index + 1) ? input.length() - index
                + 1 : count;
        return input.substring(index - 1, index + count - 1);
    }

    /**
     * Unicode转换成GBK字符集
     *
     * @param input
     *            待转换字符串
     * @return 转换完成字符串
     */
    public static String UnicodeToGB(String input)
            throws UnsupportedEncodingException {
        if (isEmpty(input)) {
            return "";
        } else {
            String s1;
            s1 = new String(input.getBytes("ISO8859_1"), "GBK");
            return s1;
        }
    }

    /**
     * GBK转换成Unicode字符集
     *
     * @param input
     *            待转换字符串
     * @return 转换完成字符串
     */
    public static String GBToUnicode(String input)
            throws UnsupportedEncodingException {
        if (isEmpty(input)) {
            return "";
        } else {
            String s1;
            s1 = new String(input.getBytes("GBK"), "ISO8859_1");
            return s1;
        }
    }

    /**
     * 分隔字符串成数组.
     * <p/>
     * 使用StringTokenizer,String的split函数不能处理'|'符号
     *
     * @param input
     *            输入字符串
     * @param delim
     *            分隔符
     * @return 分隔后数组
     */
    public static String[] splitString(String input, String delim) {
        if (isEmpty(input)) {
            return new String[0];
        }
        ArrayList al = new ArrayList();
        for (StringTokenizer stringtokenizer = new StringTokenizer(input, delim); stringtokenizer
                .hasMoreTokens(); al.add(stringtokenizer.nextToken())) {
        }
        String result[] = new String[al.size()];
        for (int i = 0; i < result.length; i++) {
            result[i] = (String) al.get(i);
        }
        return result;
    }

    /**
     * 判断字符串数组中是否包含某字符串元素
     *
     * @param substring
     *            某字符串
     * @param source
     *            源字符串数组
     * @return 包含则返回true,否则返回false
     */
    public static boolean isIn(String substring, String[] source) {
        if (source == null || source.length == 0) {
            return false;
        }
        for (int i = 0; i < source.length; i++) {
            String aSource = source[i];
            if (aSource.equals(substring)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 判断字符是否为空
     *
     * @param input
     *            某字符串
     * @return 包含则返回true,否则返回false
     */
    public static boolean isEmpty(String input) {
        return input == null || input.length() == 0;
    }

    /**
     * 获得0-9的随机数
     *
     * @param length
     * @return String
     */
    public static String getRandomNumber(int length) {
        Random random = new Random();
        StringBuffer buffer = new StringBuffer();

        for (int i = 0; i < length; i++) {
            buffer.append(random.nextInt(10));
        }
        return buffer.toString();
    }

    /**
     * 获得0-9的随机数 长度默认为10
     *
     * @return String
     */
    public static String getRandomNumber() {
        return getRandomNumber(10);
    }

    /**
     * 获得0-9,a-z,A-Z范围的随机数
     *
     * @param length
     *            随机数长度
     * @return String
     */

    public static String getRandomChar(int length) {
        char[] chr = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a',
                'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
                'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y',
                'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
                'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
                'X', 'Y', 'Z' };

        Random random = new Random();
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < length; i++) {
            buffer.append(chr[random.nextInt(62)]);
        }
        return buffer.toString();
    }

    public static String getRandomChar() {
        return getRandomChar(10);
    }

    public static String getPrimaryKey() {
        Date now = new Date();
        SimpleDateFormat dateformat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        return dateformat.format(now) + getRandomChar(13);
    }

    public static String filterHTML(String input) {
        StringBuffer filtered = new StringBuffer();
        char c;
        for (int i = 0; i <= input.length() - 1; i++) {
            c = input.charAt(i);
            switch (c) {
            case '&':
                filtered.append("&amp;");
                break;
            case '<':
                filtered.append("&lt;");
                break;
            case '>':
                filtered.append("&gt;");
                break;
            case '"':
                filtered.append("&#034;");
                break;
            case '\'':
                filtered.append("&#039;");
                break;
            default:
                filtered.append(c);
            }
        }
        return (filtered.toString());
    }

    static public String prefixZoreFill(String sourceStr, int len) {
        int prefix = len - sourceStr.length();
        if (prefix <= 0)
            return sourceStr;
        for (int i = 0; i < prefix; i++) {
            sourceStr = "0" + sourceStr;
        }
        return sourceStr;
    }

    static public String replaceAll(String str, String regex, String replacement) {
        if (str == null || str.compareTo("") == 0 || str.compareTo("null") == 0) {
            return str;
        }
        if (regex == null || regex.compareTo("null") == 0) {
            return str;
        }
        if (replacement == null || replacement.compareTo("null") == 0) {
            return str;
        }

        try {
            int iIndex, iFromIndex;
            String stmp = new String();
            ;
            int iLen = regex.length();

            iFromIndex = 0;
            iIndex = str.indexOf(regex, iFromIndex);
            stmp = "";
            while (iIndex >= 0) {
                stmp = stmp + str.substring(iFromIndex, iIndex) + replacement;
                str = str.substring(iIndex + iLen);
                iIndex = str.indexOf(regex, iFromIndex);
            }
            stmp = stmp + str;

            return stmp;
        } catch (Exception e) {
            return str;
        }
    }

    static public int length(String str) {
        if (str == null || str.compareTo("") == 0 || str.compareTo("null") == 0) {
            return 0;
        }

        int enLen = 0;
        int chLen = 0;
        char ch = ' ';
        Character CH = new Character(' ');
        int iValue = 0;

        for (int i = 0; i < str.length(); i++) {
            ch = str.charAt(i);
            CH = new Character(ch);
            iValue = CH.charValue();
            if (iValue < 128) {
                enLen++;
            } else {
                chLen++;
            }
        }

        return (enLen + chLen / 2);
    }

    static public String substring(String str, int beginIndex, int endIndex) {
        if (str == null || str.compareTo("") == 0 || str.compareTo("null") == 0) {
            return "";
        }

        String rtsValue = null;
        int enLen = 0;
        int chLen = 0;
        char ch = ' ';
        Character CH = new Character(' ');
        int iValue = 0;
        int iLength = 0;
        int realBegin = 0;
        int realEnd = 0;
        int i = 0;

        while (iLength < beginIndex) {
            ch = str.charAt(i);
            CH = new Character(ch);
            iValue = CH.charValue();
            if (iValue < 128) {
                enLen++;
            } else {
                chLen++;
            }
            iLength = enLen + chLen / 2;
            i++;
        }

        realBegin = enLen + chLen;

        i = realBegin;
        while (iLength < endIndex) {
            ch = str.charAt(i);
            CH = new Character(ch);
            iValue = CH.charValue();
            if (iValue < 128) {
                enLen++;
            } else {
                chLen++;
            }
            iLength = enLen + chLen / 2;
            i++;
        }

        realEnd = enLen + chLen;

        rtsValue = str.substring(realBegin, realEnd);

        return rtsValue;
    }

    public static int parseInt(String s) {
        try {
            return Integer.parseInt(s);
        } catch (Exception e) {
            return 0;
        }
    }

    public static List splitStringToList(String input, String delim) {
        if (isEmpty(input)) {
            return null;
        }
        ArrayList list = new ArrayList();
        for (StringTokenizer stringtokenizer = new StringTokenizer(input, delim); stringtokenizer
                .hasMoreTokens(); list.add(stringtokenizer.nextToken())) {
        }
        return list;
    }

    /**
     *转换数字或字母为固定长度的字符串
     *
     * @param str
     * @param len
     * @return
     */
    public static String transformString(String str, int len) {
        int preLen = str.length();
        len = len - preLen;
        for (int i = 0; i < len; i++) {
            str = str + " ";
        }
        return str;
    }

    /**
     * 转换汉字为固定长度的字符串
     *
     * @param str
     * @param len
     * @return
     */
    public static String transNameToString(String str, int len) {
        int preLen = str.length() * 2;
        len = len - preLen;
        for (int i = 0; i < len; i++) {
            str = str + " ";
        }
        return str;
    }

    // Replace
    public static String Replace(String source, String oldString,
            String newString) {
        if (source == null)
            return null;
        StringBuffer output = new StringBuffer();
        int lengOfsource = source.length();
        int lengOfold = oldString.length();
        int posStart = 0;
        int pos;
        while ((pos = source.indexOf(oldString, posStart)) >= 0) {
            output.append(source.substring(posStart, pos));
            output.append(newString);
            posStart = pos + lengOfold;
        }
        if (posStart < lengOfsource) {
            output.append(source.substring(posStart));
        }
        return output.toString();
    }

    public static String toHtml(String s) {
        s = Replace(s, "&", "&amp;");
        s = Replace(s, "<", "&lt;");
        s = Replace(s, ">", "&gt;");
        s = Replace(s, "\t", "    ");
        s = Replace(s, "\r\n", "\n");
        s = Replace(s, "\n", "<br>");
        s = Replace(s, "  ", " &nbsp;");
        s = Replace(s, "'", "&#39;");
        s = Replace(s, "\\", "&#92;");
        return s;
    }

    public static String unHtml(String s) {
        s = Replace(s, "&amp;", "&");
        s = Replace(s, "&lt;", "<");
        s = Replace(s, "&gt;", ">");
        s = Replace(s, "    ", "\t");
        s = Replace(s, "\n", "\r\n");
        s = Replace(s, "<br>", "\n");
        s = Replace(s, " &nbsp;", "  ");
        s = Replace(s, "&#39;", "'");
        s = Replace(s, "&#92;", "\\");
        return s;
    }

    // public static String unHtml(String s) {
    // s = Replace(s, "<br>", "\n");
    // s = Replace(s, "&nbsp;", " ");
    // return s;
    // }
    /**
     *
     * @param s
     * @return 去掉标记
     */
    public static String outTag(final String s) {
        if(s==null)
            return "";
        return s.replaceAll("<.*?>", "").replaceAll("/[a-z|A-Z]>", "");
    }
//    public static String outHtml(String s) {
//        String temp = s;
//        int a = 0, b = 0;
//        try {
//            for (int i = 0; i < s.length(); i++) {
//                a = temp.indexOf('<');
//                b = temp.indexOf('>');
//                if (a == -1 || b == -1)
//                    break;
//                else if (a < b) {
//                    // System.out.println(temp.substring(a,b+1));
//                    temp = Replace(temp, temp.substring(a, b + 1), "");
//                }
//            }
//        } catch (Exception e) {
//            System.out.println(e.getMessage());
//            return "";
//        }
//        return temp;
//    }

    public static String chsql(String message) {
        message = message.replace('<', '_');
        message = message.replace('>', '_');
        message = message.replace('"', '_');
        message = message.replace('\'', '_');
        message = message.replace('%', '_');
        message = message.replace(';', '_');
        message = message.replace('(', '_');
        message = message.replace(')', '_');
        message = message.replace('&', '_');
        message = message.replace('+', '_');
        return message;
    }

    public static String Az(String str) {
        if (str.matches("[a-z]+"))
            return str;
        else
            return "";
    }

    public static String num(String html) {
        if (html.matches("[0-9]+"))
            return html;
        else
            return "";
    }

    public static String Az09(String str) {
        if (str.matches("[a-z0-9]+"))
            return str;
        else
            return "";
    }
     /**
     *    If the given Object is no Array, it's toString - method is invoked.
     *    Primitive type - Arrays and Object - Arrays are introspected using java.lang.reflect.Array.
     * Convention for creation fo String - representation: <br>
     * <pre>
     * Primitive Arrays:    "["+isArr[0]+","+isArr[1]+.. ..+isArr[isArr.length-1]+"]"
     *
     *
     * Object Arrays :         "["+isArr[0].toString()+","+isArr[1].toString()+.. ..+isArr[isArr.length-1].toString+"]"
     *                        Two or three - dimensional Arrays are not supported (should be reflected in a special output method, e.g.as a field)
     * other Objects:        toString()
     * </pre>
     * @param   isArr  The Array to represent as String.
     * @return  A String-represetation of the Object
     */
    public static final String ArrayToString(Object isArr) {
        if(isArr==null)return "null";
        Object element;
        StringBuffer tmp = new StringBuffer();
        try {
            int length = Array.getLength(isArr);
            tmp.append("[");
            for(int i=0;i<length;i++) {
                element = Array.get(isArr,i);
                if(element==null)
                    tmp.append("null");
                else
                    tmp.append(element.toString());
                if(i<length-1)tmp.append(",");
            }
            tmp.append("]");
        }catch(ArrayIndexOutOfBoundsException bound) {
            tmp.append("]");    //programming mistake or bad Array.getLength(obj).
            return tmp.toString();
           
        }catch(IllegalArgumentException noarr) {
            return isArr.toString();
        }
        return tmp.toString();
    }
//    /**
//     *
//     * @param s
//     * @return 获得网页标题
//     */
//    public static String getH1(String html) {
//        //if(html==null)return "";
//        String regex,tmp;
//        StringBuffer str=new StringBuffer();
//        final List<String> list = new ArrayList<String>();
//        regex = "<h1.*?</h1>";
//        final Pattern pa = Pattern.compile(regex, Pattern.CANON_EQ);
//        final Matcher ma = pa.matcher(html);
//        while (ma.find()) {
//            list.add(ma.group());
//        }
//        for (int i = 0; i < list.size(); i++) {
//            tmp=outTag(list.get(i));
//            if(!"".equals(tmp))
//            str.append("<h1>"+tmp+"</h1>");
//            //str = str + "<h1>"+outTag(list.get(i))+"</h1>";
//        }
//        return str.toString();
//    }
//    public static String getH2(String html) {
//        //if(html==null)return "";
//        String regex,tmp;
//        StringBuffer str=new StringBuffer();
//        final List<String> list = new ArrayList<String>();
//        regex = "<h2.*?</h2>";
//        final Pattern pa = Pattern.compile(regex, Pattern.CANON_EQ);
//        final Matcher ma = pa.matcher(html);
//        while (ma.find()) {
//            list.add(ma.group());
//        }
//        for (int i = 0; i < list.size(); i++) {
//            tmp=outTag(list.get(i));
//            if(!"".equals(tmp))
//            str.append("<h2>"+tmp+"</h2>");
//            //str = str + "<h2>"+outTag(list.get(i))+"</h2>";
//        }
//        return str.toString();
//    }
//    public static String getH3(String html) {
//        //if(html==null)return "";
//        String regex,tmp;
//        StringBuffer str=new StringBuffer();
//        final List<String> list = new ArrayList<String>();
//        regex = "<h3.*?</h3>";
//        final Pattern pa = Pattern.compile(regex, Pattern.CANON_EQ);
//        final Matcher ma = pa.matcher(html);
//        while (ma.find()) {
//            list.add(ma.group());
//        }
//        for (int i = 0; i < list.size(); i++) {
//            tmp=outTag(list.get(i));
//            if(!"".equals(tmp))
//            str.append("<h3>"+tmp+"</h3>");
//            //str = str + "<h3>"+outTag(list.get(i))+"</h3>";
//        }
//        return str.toString();
//    }
//    public static String getB(String html) {
//        //if(html==null)return "";
//        String regex,tmp;
//        StringBuffer str=new StringBuffer();
//        final List<String> list = new ArrayList<String>();
//        regex = "<b.*?</b>";
//        final Pattern pa = Pattern.compile(regex, Pattern.CANON_EQ);
//        final Matcher ma = pa.matcher(html);
//        while (ma.find()) {
//            list.add(ma.group());
//        }
//        for (int i = 0; i < list.size(); i++) {
//            tmp=outTag(list.get(i));
//            if(!"".equals(tmp))
//            str.append("<b>"+tmp+"</b>");
//            //str = str + "<b>"+outTag(list.get(i))+"</b>";
//        }
//        return str.toString();
//    }
//    public static String getStrong(String html) {
//        //if(html==null)return "";
//        String regex,tmp;
//        StringBuffer str=new StringBuffer();
//        final List<String> list = new ArrayList<String>();
//        regex = "<strong.*?</strong>";
//        final Pattern pa = Pattern.compile(regex, Pattern.CANON_EQ);
//        final Matcher ma = pa.matcher(html);
//        while (ma.find()) {
//            list.add(ma.group());
//        }
//       
//        for (int i = 0; i < list.size(); i++) {
//            tmp=outTag(list.get(i));
//            if(!"".equals(tmp))
//            str.append("<strong>"+tmp+"</strong>");
//            //str = str + "<strong>"+outTag(list.get(i))+"</strong>";
//        }
//        return str.toString();
//    }
//    public static String getP(String html) {
//        //if(html==null)return "";
//        String regex,tmp;
//        StringBuffer str=new StringBuffer();
//        final List<String> list = new ArrayList<String>();
//        regex = "<p.*?</p>";
//        final Pattern pa = Pattern.compile(regex, Pattern.CANON_EQ);
//        final Matcher ma = pa.matcher(html);
//        while (ma.find()) {
//            list.add(ma.group());
//        }
//        for (int i = 0; i < list.size(); i++) {
//            tmp=outTag(list.get(i));
//            if(!"".equals(tmp))
//            str.append("<p>"+tmp+"</p>");
//        }
//        return str.toString();
//    }
 // GENERAL_PUNCTUATION 判断中文的“号 //
    // CJK_SYMBOLS_AND_PUNCTUATION 判断中文 的。号 /
    // HALFWIDTH_AND_FULLWIDTH_FORMS 判断中文的,号

    public static boolean isChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
                || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
            return true;
        }
        return false;
    }
    //是否是乱码
    public static boolean isMessyCode(String strName) {
        Pattern p = Pattern.compile("\\s*|\t*|\r*|\n*");
        Matcher m = p.matcher(strName);
        String after = m.replaceAll("");
        //System.out.println("after=======" + after);
        //System.out.println("=======================");
        String temp = after.replaceAll("\\p{P}", "");
        //System.out.println("temp=======" + temp);

        char[] ch = temp.trim().toCharArray();
        float chLength = ch.length;
        //System.out.println("chLength=" + chLength);
        float count = 0;
        for (int i = 0; i < ch.length; i++) {
            char c = ch[i];
            if (!Character.isLetterOrDigit(c)||c!='?') { // 确定指定字符是否为字母或数字或?号
                if (!isChinese(c)) {
                    count = count + 1;
                }
            }
        }
        //System.out.println("count=" + count);
        float result = count / chLength;
        //System.out.println(result);
        if (result > 0.4) { //.4
            return true;
        } else {
            return false;
        }

    }
    public static String notNull(String text){
        if("null".equals(text)||text==null)
            return "";
        else
            return text;
    }
    public static String find4D(String string){
        String pattern="[^〔|^(|^(](\\d{4})";
        Pattern pa = Pattern.compile(pattern, Pattern.DOTALL);
        Matcher ma = pa.matcher(string);
        if(ma.find()){
            string= ma.group();
        }
        if(string!=null&&string.length()>4)
            return string.substring(1,5);
        return "";
    }
   

    public static void main(String[] args) throws UnsupportedEncodingException{
     
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值