项目开发中StringUtil工具类常见方法

package com.chang.util;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *   与操作字符串相关的工具类
 */
public class StringUtils {
    public static int DEFAULT_INT = -100;

    /**
     *  MD5 加密
     * @param str  需要加密的字符串
     * @return    返回的是32位的字符串  485f5aea8dd4a28ccad51671754b9f2b
     */
    public static String getMD5(String str) {
        StringBuffer buf = new StringBuffer("");
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(str.getBytes());
            byte b[] = md.digest();
            int i;
            for (byte aB : b) {
                i = aB;
                if (i < 0) i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        String sign = buf.toString();
        return sign;
    }

    /**
     * 检查手机号是否是11位
     * @param phoneNum
     * @return
     */
    public static boolean checkMobile(String phoneNum) {
        if(isNullOrEmpty(phoneNum)){
            return false;
        }
        Pattern p = Pattern.compile("^1[3|4|5|7|8]\\d{9}$");
        Matcher m = p.matcher(phoneNum);
        return m.matches();
    }

    /**
     * 对手机号进行加密
     * @param phoneNum
     * @return
     */
    public static String getEncryptMobile(String phoneNum) {
        if (!checkMobile(phoneNum)) {
            return phoneNum;
        }
        StringBuilder stringBuilder = new StringBuilder(phoneNum.substring(0, 3));
        stringBuilder.append("****");
        stringBuilder.append(phoneNum.substring(7));
        return stringBuilder.toString();
    }

    /**
     * 验证身份证号码格式是否正确
     * @param idCard 居民身份证号码15位或18位,最后一位可能是数字或字母
     * @return 验证成功返回true,验证失败返回false
     */
    public static boolean checkIdCard(String idCard) {
        if (idCard.length() != 15 && idCard.length() != 18) {
            return false;
        }
        String regex = "[1-9]\\d{13,16}[a-zA-Z0-9]{1}";
        return Pattern.matches(regex, idCard);
    }

    /**
     * 验证字符串合法性
     * @param str  需要验证的字符串
     * @param test 非法字符串(如:"~!#$%^&*()',;:?")
     * @return true:非法;false:合法
     * @since 1.0
     */
    public static boolean check(String str, String test) {
        if (str == null || str.equals(""))
            return true;
        boolean flag = false;
        for (int i = 0; i < test.length(); i++) {
            if (str.indexOf(test.charAt(i)) != -1) {
                flag = true;
                break;
            }
        }
        return flag;
    }

    /**
     * 去除字符串两边的空格和制表符
     */
    public static String trim(String str) {
        return str == null ? null : str.trim();
    }

    /**
     * 判断多个字符串是否都为空和空串,如果有一个不符合则为true
     * @param strArray
     * @return
     */
    public static boolean isNullOrEmptyAll(String... strArray) {
        boolean result = false;
        for (String str : strArray) {
            if (isNullOrEmpty(str)) {
                result = true;
                break;
            } else {
                result = false;
            }
        }
        return result;
    }

    /**
     * 判断字符串是否为null或者是否为空串,如果是返回true
     * @param str
     * @return
     */
    public static boolean isNullOrEmpty(String str) {
        return str == null || ("").equals(str.trim());
    }

    /**
     * 判断两个字符串是否相等,如果有一个为null或者“”或者空串,另一个为NUll或者“”或者空串也为true
     * @param s1
     * @param s2
     * @return
     */
    public static boolean isEqual(String s1, String s2) {
        if (isNullOrEmpty(s1) && !isNullOrEmpty(s2)) {
            return false;
        }
        if (!isNullOrEmpty(s1) && isNullOrEmpty(s2)) {
            return false;
        }
        if (isNullOrEmpty(s1) && isNullOrEmpty(s2)) {
            return true;
        }
        if (s1.equals(s2)) {
            return true;
        }
        return false;
    }

    /**
     * 判断两个字符串是否不相等,如果有一个为null或者“”或者空串,另一个为NUll或者“”或者空串也为false
     * @param s1
     * @param s2
     * @return
     */
    public static boolean isNotEqual(String s1, String s2) {
        if (isNullOrEmpty(s1) && !isNullOrEmpty(s2)) {
            return true;
        }
        if (!isNullOrEmpty(s1) && isNullOrEmpty(s2)) {
            return true;
        }

        if (isNullOrEmpty(s1) && isNullOrEmpty(s2)) {
            return false;
        }
        if (s1.equals(s2)) {
            return false;
        }
        return true;
    }

    /**
     * 将数值型转换成字符串
     * @param it  需要转换的Integer型值
     * @param ret 转换失败的返回值
     * @return 成功则返回转换后的字符串;失败则返回ret
     */
    public static String integerToString(Integer it, String ret) {
        try {
            return Integer.toString(it);
        } catch (NumberFormatException e) {
            return ret;
        }
    }

    /**
     * list转String,集合元素以分隔符sign进行分割
     * @param list
     * @param sign 分隔符号,可为“”
     * @return   2131,45321,2313490
     */
    public static String listToString(List<String> list, String sign) {
        if (list == null || list.size() == 0)
            return null;
        StringBuffer sb = new StringBuffer();
        for (String string : list) {
            sb.append(string).append(sign);
        }
        return sb.substring(0, sb.length() - 1);
    }

    /**
     * String转list 去除null 空串
     * @param target 2131453,21231349
     * @param sign   分隔符号 ,
     * @return  2131453  21231349
     */
    public static List<String> stringToList(String target, String sign) {
        List<String> usersList = new ArrayList<String>();
        if (!StringUtils.isNullOrEmpty(target)) {
            String[] vs = target.split(sign);
            for (String v : vs) {
                if (!StringUtils.isNullOrEmpty(v))
                    usersList.add(v);
            }
        }
        return usersList;
    }

    /**
     * 将浮点数进行四舍五入
     * @return 改写后的字符串
     */
    public static String doubleToString(double str) {
        return doubleToString(str, 2);
    }

    /**
     * 将String类型转成long类型
     * @param o
     * @param defaultValue  转换失败的默认值
     * @return
     */
    public static long getLongValue(String o, long defaultValue) {
        if (!isNullOrEmpty(o)) {
            try {
                return Long.parseLong(String.valueOf(o));
            } catch (Exception e) {
            }
        }
        return defaultValue;
    }

    /**
     * 将字符串strSC按照字符串splitStr切割成数组,如果数组的元素有str则返回true
     */
    public static boolean isContain(String strSc, String str, String splitStr) {
        String split = ",";
        if (!isNullOrEmpty(splitStr)) {
            split = splitStr;
        }
        if (!isNullOrEmptyAll(strSc, str)) {
            String[] strs = strSc.split(split);
            for (String newStr : strs) {
                if (newStr.trim().equals(str)) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 判断list集合中是否包含某一个字符串str
     * @param list
     * @param str
     * @return
     */
    public static boolean listContain(List list, String str) {
        return !(list == null || list.size() == 0) && list.contains(str);
    }

    /**
     * 将一字符串数组以某特定的字符串token作为分隔来变成字符串
     * @param strs  字符串数组
     * @param token 分隔字符串
     * @return 以token为分隔的字符串
     */
    public static String join(String[] strs, String token) {
        if (strs == null)
            return null;
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < strs.length; i++) {
            if (i != 0)
                sb.append(token);
            sb.append(strs[i]);
        }
        return sb.toString();
    }

    /**
     * 截取指定长度 从0开始,包左不包右
     */
    public static String splite(String str, int start, int end) {
        CharSequence sequence = str.subSequence(start, end);
        return sequence.toString();
    }

    /**
     * 比较两字符串大小(ASCII码顺序)
     * @param str1 参与比较的字符串1
     * @param str2 参与比较的字符串2
     * @return str1>str2:1;str1<str2:-1;str1=str2:0
     */
    public static int compare(String str1, String str2) {//
        if (str1.equals(str2)) {
            return 0;
        }
        int str1Length = str1.length();
        int str2Length = str2.length();
        int length = 0;
        if (str1Length > str2Length) {
            length = str2Length;
        } else {
            length = str1Length;
        }
        for (int i = 0; i < length; i++) {
            if (str1.charAt(i) > str2.charAt(i)) {
                return 1;
            }
        }
        return -1;
    }

    /**
     * 将一字符串以某特定的字符串作为分隔来变成字符串数组
     * @param str   需要拆分的字符串("@12@34@56")
     * @param token 分隔字符串("@")
     * @return 以token为分隔的拆分开的字符串数组
     * @since 1.0
     */
    public static String[] split(String str, String token) {
        String temp = str.substring(1, str.length());
        return temp.split(token);
    }

    /**
     * 将不同数据合并成字符串
     * @param obj 要合并的数据,可以是多个不同类型的基本类型,引用类型除外
     * @return 拼接后的字符串 String
     */
    public static String getMerge(Object... obj) {
        StringBuffer mStringBuffer = new StringBuffer();
        for (Object anObj : obj) {
            mStringBuffer.append(anObj);
        }
        return mStringBuffer.toString();
    }

    /**
     * 将字符串中所有老的字符串替换成新的字符串
     * @param str     需要进行替换的字符串
     * @param oldStr 老的字符串,可以多个字符
     * @param newStr 新的字符串,可以多个字符
     * @return 替换后对应的字符串
     */
    public static String replace(String str, String oldStr, String newStr) {
        String ret = str;
        if (ret != null && oldStr != null && newStr != null) {
            ret = str.replaceAll(oldStr, newStr);
        }
        return ret;
    }

    /**
     * 替换字符串,将字符串中oldStr替换成newStr(可为$)
     * 修复java.lang.String类的replaceAll方法时第一参数是字符串常量正则时(如:"address".
     * replaceAll("dd","$");)的抛出异常:java.lang.StringIndexOutOfBoundsException:
     * String index out of range: 1的问题。
     * @param strSc  需要进行替换的字符串
     * @param oldStr 源字符串
     * @param newStr 替换后的字符串
     * @return 替换后对应的字符串
     */
    public static String replaceAll(String strSc, String oldStr, String newStr) {
        int i = -1;
        while ((i = strSc.indexOf(oldStr)) != -1) {
            strSc = new StringBuffer(strSc.substring(0, i)).append(newStr)
                    .append(strSc.substring(i + oldStr.length())).toString();
        }
        return strSc;
    }

    /**
     * 将字符串的首字母改为大写
     * @param str 需要改写的字符串
     * @return 改写后的字符串
     */
    public static String firstToUpper(String str) {
        return str.substring(0, 1).toUpperCase() + str.substring(1);
    }

    /**
     * 将字符串str根据split条件拆分成数组,然后各个数组元素有包含condition字符串的返回第一个元素
     */
    public static String getStrSplitByCondition(String str, String split, String condition) {
        String[] cookieArr = str.split(split);
        String result = "";
        for (int i = 0; i < cookieArr.length; i++) {
            if (cookieArr[i].contains(condition)) {
                return cookieArr[i];
            }
        }
        return result;
    }

    /**
     *  在字符串str从第四个位置开始,每隔5插入字符串split
     * @param str
     * @param split  插入字符串split
     * @return
     */
    public static String getSplitString(String str, String split) {
        StringBuilder stringBuilder = new StringBuilder(str);
        for (int i = 4; i < stringBuilder.length(); i += 5) {
            stringBuilder.insert(i, split);
        }
        return stringBuilder.toString();
    }

    public static String subZeroAndDot(String s) {
        if (s.indexOf(".") > 0) {
            s = s.replaceAll("0+?$", "");//去掉多余的0
            s = s.replaceAll("[.]$", "");//如最后一位是.则去掉
        }
        return s;
    }



    //将float类型转成0.00格式    1.20
    public static String formatNum(float num) {
        DecimalFormat decimalFormat = new DecimalFormat("0.00");
        return decimalFormat.format(num);
    }

    //将int类型转成1222.00格式
    public static String numToString(int str) {
        return doubleToString(str, 2);
    }

    //将double类型进行四舍五入  offset保留几位
    public static String doubleToString(double str, int offset) {
        return new BigDecimal(str + "").setScale(offset,
                BigDecimal.ROUND_HALF_UP).toString();
    }

    public static Date stringDateTodate(String date) {
        String time = date.substring(6, date.length() - 7);
        return new Date(Long.parseLong(time));
    }

    /**
     * 判断字符串是否含有中文字符
     */
    public static final boolean isContainChinese(String strName) {
        char[] ch = strName.toCharArray();
        for (char c : ch) {
            if (isChinese(c)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取中文汉字,拼接成字符串
     * @param str
     * @return
     */
    public static String getChinese(String str) {
        char[] chars = str.toCharArray();
        StringBuilder chinese = new StringBuilder();
        for (char aChar : chars) {
            if (isChinese(aChar)) {
                chinese.append(aChar);
            }
        }
        return chinese.toString();
    }

    /**
     * 如果值以【或者[开头的将其以-返回,其他的以原字符串返回
     * @param str
     * @return
     */
    public static String convertValue(String str) {
        if (str.startsWith("[") || str.startsWith("【")) {
            return "-";
        }
        return trim(str);
    }

    /**
     * 判断字符串是否为数字(含小数)
     */
    public static boolean isNumber(String str) {
        //Pattern pattern = Pattern.compile("^-?[0-9]+"); //这个也行
        Pattern pattern = Pattern.compile("^[0-9]+.?[0-9]*$");//这个也行
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }

    /**
     * 字符串是否有中文字符
     * @param str
     * @return
     */
    public static boolean hasChineseChar(String str) {
        boolean temp = false;
        Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
        Matcher m = p.matcher(str);
        if (m.find()) {
            temp = true;
        }
        return temp;
    }

    /**
     * 字符是否是中文字符
     * <p/>
     * 不包括““”号,“。”号,“,”号
     * <p/>
     * GENERAL_PUNCTUATION 判断中文的“号
     * <p/>
     * CJK_SYMBOLS_AND_PUNCTUATION 判断中文的。号
     * <p/>
     * HALFWIDTH_AND_FULLWIDTH_FORMS 判断中文的,号
     */
    private static final boolean isChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        return ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A;
    }

    /**
     * 格式化数字,结果可能不正确,会进行四舍五入    182w   1.7k
     * @param num (int)
     */
    public static String simpleFormat(int num) {
        DecimalFormat df = new DecimalFormat("#.#");
        StringBuilder numFormat = new StringBuilder();
        double numDouble;
        if (num > 1000 && num < 10000) {//1千以上
            numDouble = num / 1000d;
            numFormat.append(df.format(numDouble)).append("k");
        } else if (num > 10000) { // 1万以上
            numDouble = num / 10000d;
            numFormat.append(df.format(numDouble)).append("w");
        } else {
            numFormat.append(num);
        }
        return numFormat.toString();
    }

    /**
     * 数字转成以万、亿为单位, 12321.34334444亿   1.0-->1; 1.1-->1.1
     * @param numStr (String)
     */
    public static String newNumFormat(String numStr) {
        if (!numStr.matches("[-]*[0-9]*[.]*[0-9]*")) {
            return numStr;
        }
        try {
           //long num = Integer.valueOf( numStr );
            return newNumFormat(new BigDecimal(numStr));
        } catch (Exception e) {
            e.printStackTrace();
            return numStr;
        }
    }

    /**
     * 数字转成以万、亿为单位,1.0-->1; 1.1-->1.1
     * @param num (int)
     */
    public static String newNumFormat(BigDecimal num) {
        final BigDecimal TEN_THOUSAND = new BigDecimal("10000");
        final BigDecimal MILLION = new BigDecimal("1000000");
        final BigDecimal TEN_MILLION = new BigDecimal("10000000");
        final BigDecimal HANDRED_MILLION = new BigDecimal("100000000");

        if (num.abs().compareTo(MILLION) <= 0 && num.abs().compareTo(TEN_THOUSAND) > 0) { // 万以上
            num = num.divide(TEN_THOUSAND);
            return num.toString() + "万";
        } else if (num.abs().compareTo(TEN_MILLION) <= 0 && num.abs().compareTo(MILLION) > 0) { // 百万以上
            num = num.divide(MILLION);
            return num.toString() + "百万";
        } else if (num.abs().compareTo(HANDRED_MILLION) <= 0 && num.abs().compareTo(TEN_MILLION) > 0) { // 千万以上
            num = num.divide(TEN_MILLION);
            return num.toString() + "千万";
        } else if (num.abs().compareTo(HANDRED_MILLION) > 0) { // 亿以上
            num = num.divide(HANDRED_MILLION);
            return num.toString() + "亿";
        } else {
            return num.toString();
        }
    }

    /**
     * 将阿拉伯数字的钱数转换成中文方式   二千三百一十五元零角
     * @param num 需要转换的钱的阿拉伯数字形式
     * @return 转换后的中文形式
     */
    public static String numToChinese(double num) {
        String result = "";
        String str = Double.toString(num);
        if (str.contains(".")) {
            String begin = str.substring(0, str.indexOf("."));
            String end = str.substring(str.indexOf(".") + 1, str.length());
            byte[] b = begin.getBytes();
            int j = b.length;
            for (int i = 0, k = j; i < j; i++, k--) {
                result += getConvert(begin.charAt(i));
                if (!"零".equals(result.charAt(result.length() - 1) + "")) {
                    result += getWei(k);
                }
            }
            for (int i = 0; i < result.length(); i++) {
                result = result.replaceAll("零零", "零");
            }
            if ("零".equals(result.charAt(result.length() - 1) + "")) {
                result = result.substring(0, result.length() - 1);
            }
            result += "元";
            byte[] bb = end.getBytes();
            int jj = bb.length;
            for (int i = 0, k = jj; i < jj; i++, k--) {
                result += getConvert(end.charAt(i));
                if (bb.length == 1) {
                    result += "角";
                } else if (bb.length == 2) {
                    result += getFloat(k);
                }
            }
        } else {
            byte[] b = str.getBytes();
            int j = b.length;
            for (int i = 0, k = j; i < j; i++, k--) {
                result += getConvert(str.charAt(i));
                result += getWei(k);
            }
        }
        return result;
    }

    /**
     * 将常规显示的字符串转换成HTML格式的字符串
     * @param str 需要进行转换的字符串
     * @return 转换后的字符串
     */
    public static String toHtml(String str) {
        String html = str;
        if (str == null || str.length() == 0) {
            return "";
        } else {
            html = replace(html, "&", "&amp;");
            html = replace(html, "<", "&lt;");
            html = replace(html, ">", "&gt;");
            html = replace(html, "\r\n", "\n");
            html = replace(html, "\n", "<br>\n");
            html = replace(html, "\"", "&quot;");
            html = replace(html, " ", "&nbsp;");
            return html;
        }
    }

    /**
     * 将HTML格式的字符串转换成常规显示的字符串
     * @param str 需要进行转换的字符串
     * @return 转换后的字符串
     */
    public static String toText(String str) {
        String text = str;
        if (str == null || str.length() == 0) {
            return "";
        } else {
            text = replace(text, "&amp;", "&");
            text = replace(text, "&lt;", "<");
            text = replace(text, "&gt;", ">");
            text = replace(text, "<br>\n", "\n");
            text = replace(text, "<br>", "\n");
            text = replace(text, "&quot;", "\"");
            text = replace(text, "&nbsp;", " ");
            text = replace(text, "&ldquo;", "“");
            text = replace(text, "&rdquo;", "”");
            return text;
        }
    }

    public static String escapeHtmlSign(String value) {
        if (value == null)
            return null;
        if (value instanceof String) {
            String result = value;
            // "'<>&
            result = result.replaceAll("&", "&amp;").replaceAll(">", "&gt;")
                    .replaceAll("<", "&lt;").replaceAll("\"", "&quot;")
                    .replaceAll("'", "&#39;");
            return result;
        } else {
            return value;
        }
    }

    public static String unEscapeHtmlSign(String value) {
        if (value == null)
            return null;
        if (value instanceof String) {
            String result = value;
            // "'<>&
            result = result.replaceAll("&amp;", "&").replaceAll("&gt;", ">")
                    .replaceAll("&lt;", "<").replaceAll("&quot;", "\"")
                    .replaceAll("&#39;", "'");
            return result;
        } else {
            return value;
        }
    }

    private static String getConvert(char num) {
        if (num == '0') {
            return "零";
        } else if (num == '1') {
            return "一";
        } else if (num == '2') {
            return "二";
        } else if (num == '3') {
            return "三";
        } else if (num == '4') {
            return "四";
        } else if (num == '5') {
            return "五";
        } else if (num == '6') {
            return "六";
        } else if (num == '7') {
            return "七";
        } else if (num == '8') {
            return "八";
        } else if (num == '9') {
            return "九";
        } else {
            return "";
        }
    }

    private static String getFloat(int num) {
        if (num == 2) {
            return "角";
        } else if (num == 1) {
            return "分";
        } else {
            return "";
        }
    }

    private static String getWei(int num) {
        if (num == 1) {
            return "";
        } else if (num == 2) {
            return "十";
        } else if (num == 3) {
            return "百";
        } else if (num == 4) {
            return "千";
        } else if (num == 5) {
            return "万";
        } else if (num == 6) {
            return "十";
        } else if (num == 7) {
            return "百";
        } else if (num == 8) {
            return "千";
        } else if (num == 9) {
            return "亿";
        } else if (num == 10) {
            return "十";
        } else if (num == 11) {
            return "百";
        } else if (num == 12) {
            return "千";
        } else if (num == 13) {
            return "兆";
        } else {
            return "";
        }
    }

    final static int BUFFER_SIZE = 4096;

    public static byte[] InputStreamTOByte(InputStream in) {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        try {
            byte[] data = new byte[BUFFER_SIZE];
            int count = -1;
            while ((count = in.read(data, 0, BUFFER_SIZE)) != -1)
                outStream.write(data, 0, count);
            data = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return outStream.toByteArray();
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值