栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

项目开发中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;

    
    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;
    }

    
    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();
    }

    
    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();
    }

    
    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);
    }

    
    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();
    }

    
    public static boolean isNullOrEmptyAll(String... strArray) {
        boolean result = false;
        for (String str : strArray) {
            if (isNullOrEmpty(str)) {
                result = true;
                break;
            } else {
                result = false;
            }
        }
        return result;
    }

    
    public static boolean isNullOrEmpty(String str) {
        return str == null || ("").equals(str.trim());
    }

    
    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;
    }

    
    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;
    }

    
    public static String integerToString(Integer it, String ret) {
        try {
            return Integer.toString(it);
        } catch (NumberFormatException e) {
            return ret;
        }
    }

    
    public static String listToString(List 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);
    }

    
    public static List stringToList(String target, String sign) {
        List usersList = new ArrayList();
        if (!StringUtils.isNullOrEmpty(target)) {
            String[] vs = target.split(sign);
            for (String v : vs) {
                if (!StringUtils.isNullOrEmpty(v))
                    usersList.add(v);
            }
        }
        return usersList;
    }

    
    public static String doubleToString(double str) {
        return doubleToString(str, 2);
    }

    
    public static long getLongValue(String o, long defaultValue) {
        if (!isNullOrEmpty(o)) {
            try {
                return Long.parseLong(String.valueOf(o));
            } catch (Exception e) {
            }
        }
        return defaultValue;
    }

    
    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;
    }

    
    public static boolean listContain(List list, String str) {
        return !(list == null || list.size() == 0) && list.contains(str);
    }

    
    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();
    }

    
    public static String splite(String str, int start, int end) {
        CharSequence sequence = str.subSequence(start, end);
        return sequence.toString();
    }

    
    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;
    }

    
    public static String[] split(String str, String token) {
        String temp = str.substring(1, str.length());
        return temp.split(token);
    }

    
    public static String getMerge(Object... obj) {
        StringBuffer mStringBuffer = new StringBuffer();
        for (Object anObj : obj) {
            mStringBuffer.append(anObj);
        }
        return mStringBuffer.toString();
    }

    
    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;
    }

    
    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;
    }

    
    public static String firstToUpper(String str) {
        return str.substring(0, 1).toUpperCase() + str.substring(1);
    }

    
    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;
    }

    
    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;
    }

    
    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();
    }

    
    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;
    }

    
    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;
    }

    
    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;
    }

    
    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();
    }

    
    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;
        }
    }

    
    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();
        }
    }

    
    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;
    }

    
    public static String toHtml(String str) {
        String html = str;
        if (str == null || str.length() == 0) {
            return "";
        } else {
            html = replace(html, "&", "&");
            html = replace(html, "<", "<");
            html = replace(html, ">", ">");
            html = replace(html, "rn", "n");
            html = replace(html, "n", "
n"); html = replace(html, """, """); html = replace(html, " ", " "); return html; } } public static String toText(String str) { String text = str; if (str == null || str.length() == 0) { return ""; } else { text = replace(text, "&", "&"); text = replace(text, "<", "<"); text = replace(text, ">", ">"); text = replace(text, "
n", "n"); text = replace(text, "
", "n"); text = replace(text, """, """); text = replace(text, " ", " "); text = replace(text, "“", "“"); text = replace(text, "”", "”"); return text; } } public static String escapeHtmlSign(String value) { if (value == null) return null; if (value instanceof String) { String result = value; // "'<>& result = result.replaceAll("&", "&").replaceAll(">", ">") .replaceAll("<", "<").replaceAll(""", """) .replaceAll("'", "'"); 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("&", "&").replaceAll(">", ">") .replaceAll("<", "<").replaceAll(""", """) .replaceAll("'", "'"); 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(); } }
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/318665.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号