java操作字符串的工具类StringUtil

导读:本篇文章讲解 java操作字符串的工具类StringUtil,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

依赖引入

        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.6</version>
        </dependency>

java对字符串操作的工具类

package com.leo.demo.othertest;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;


public class StringUtil extends org.apache.commons.lang.StringUtils {
    public static final String TA_LEFT = "left";
    public static final String TA_RIGHT = "right";

    /**
     * 获取流水号:4位平台机构编码+14位组包时间YYYYMMDDHH24MMSS+6位流水号(定长),序号随机
     *
     * @return
     */
    public static String getIndictseq() {
        StringBuilder indictseq = new StringBuilder("1085");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String dateString = sdf.format(new Date());
        indictseq.append(dateString);
        StringBuilder smsCode = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            int x = (int) (Math.random() * 10);
            smsCode.append(x);
        }
        indictseq.append(smsCode);
        return indictseq.toString();
    }

    /**
     * 字符串按指定长度构造字符串,不足填空格
     *
     * @param str
     * @param len
     * @param align
     * @return
     */
    public static String toStringAlign(String str, int len, String align) {
        String AlignText = new String(str);
        if (AlignText.length() < len) {
            int Count = len - AlignText.length();
            while (Count > 0) {
                if (StringUtil.equalsIgnoreCase(align, StringUtil.TA_LEFT)) AlignText = AlignText + " ";
                else AlignText = " " + AlignText;
                Count--;
            }
        }
        return AlignText;

    }

    /**
     * 整数按指定长度构造字符串,不足填空格
     *
     * @param iVal
     * @param len
     * @param align left,right
     * @return String
     */
    public static String toStringAlign(int iVal, int len, String align) {
        return StringUtil.toStringAlign(String.valueOf(iVal), len, align);
    }

    /**
     * 长整数按指定长度构造字符串,不足填空格
     *
     * @param lVal
     * @param len
     * @param align
     * @return
     */
    public static String toStringAlign(long lVal, int len, String align) {
        return StringUtil.toStringAlign(String.valueOf(lVal), len, align);
    }

    /**
     * 从字符串中删除掉指定字符
     *
     * @param str
     * @param ch
     * @return
     */
    public static String remove(String str, char ch) {
        String temp = "";
        int Index = 0;
        while (Index < str.length()) {
            if (str.charAt(Index) != ch)
                temp = temp + String.valueOf(str.charAt(Index));
            Index++;
        }
        return temp;
    }

    /**
     * 从字符串中删除掉指定字符串
     *
     * @param str
     * @param RevStr
     * @return
     */
    public static String remove(String str, String RevStr) {
        return StringUtil.replace(str, RevStr, "");
    }

    /**
     * 整数按指定长度构造字符串,以字符填空格
     *
     * @param str
     * @param len
     * @param align
     * @param full
     * @return
     */
    public static String fullStringAlgin(String str, int len, String align, char full) {
        String temp = str;
        if (temp.length() < len) {
            int nCount = len - temp.getBytes().length;
            String fullstr = String.valueOf(full);
            while (nCount > 0) {
                if (StringUtil.equalsIgnoreCase(align, StringUtil.TA_LEFT)) temp = temp + fullstr;
                else temp = fullstr + temp;
                nCount--;
            }
        }
        return temp;
    }

    /**
     * 字符串中是否包含指定字符串(忽虑字符大小写)
     *
     * @param str1
     * @param str2
     * @return
     */
    public static boolean containsIgnoreCase(String str1, String str2[]) {
        boolean aEnable = false;
        for (int index = 0; index < str2.length; index++)
            aEnable |= StringUtil.equalsIgnoreCase(str1, str2[index]) ? true : false;
        return aEnable;
    }

    /**
     * 字符串中是否包含指定字符串
     *
     * @param str1
     * @param str2
     * @return
     */
    public static boolean contains(String str1, String str2[]) {
        boolean aEnable = false;
        for (int index = 0; index < str2.length; index++)
            aEnable |= StringUtil.equals(str1, str2[index]) ? true : false;
        return aEnable;
    }

    /**
     * 判断字符串在尾部是否以指定字符串
     *
     * @param str1
     * @param str2
     * @return
     */
    public static boolean endsWith(String str1, String str2) {
        if (str1 == null || str2 == null) return false;
        if (str1.length() < str2.length()) return false;
        for (int index = 0; index < str2.length(); index++) {
            if (str1.charAt(str1.length() - index - 1) != str2.charAt(str2.length() - 1 - index)) return false;
        }
        return true;
    }

    /**
     * 判断字符串在尾部是否以指定字符串(忽虑字符大小写)
     *
     * @param str1
     * @param str2
     * @return
     */
    public static boolean endsIgnoreCaseWith(String str1, String str2) {
        if (str1 == null || str2 == null) return false;
        if (str1.length() < str2.length()) return false;
        return StringUtil.endsWith(str1.toUpperCase(), str2.toUpperCase());
    }

    /**
     * 判断字符串在开头是否以指定字符串
     *
     * @param str1
     * @param str2
     * @return
     */
    public static boolean startWith(String str1, String str2) {
        if (str1 == null || str2 == null) return false;
        if (str1.length() < str2.length()) return false;
        for (int Index = 0; Index < str2.length(); Index++)
            if (str1.charAt(Index) != str2.charAt(Index)) return false;
        return true;
    }

    /**
     * 判断字符串在开头是否以指定字符串(忽虑字符大小写)
     *
     * @param str1
     * @param str2
     * @return
     */
    public static boolean startIgnoreCaseWith(String str1, String str2) {
        if (str1 == null || str2 == null) return false;
        if (str1.length() < str2.length()) return false;
        return StringUtil.startWith(str1.toUpperCase(), str2.toUpperCase());
    }

    /**
     * 判断字符串中是否包含指定字符串(忽虑字符大小写)
     *
     * @param lpBuffer
     * @param containsbuff
     * @return
     */
    public static boolean containsIgnoreCase(String lpBuffer, String containsbuff) {
        boolean RetCode = false;
        if (containsbuff == null || containsbuff.length() <= 0) return true;
        if (lpBuffer == null || lpBuffer.length() <= 0 || lpBuffer.length() < containsbuff.length()) return false;
        int Index = 0;
        String temp;
        while (Index < lpBuffer.length()) {
            temp = StringUtil.mid(lpBuffer, Index, containsbuff.length());
            if (StringUtil.equalsIgnoreCase(temp, containsbuff) == true) return true;
            Index++;
        }
        return RetCode;
    }

    /**
     * 是否包含指定字符串(忽略空格字符串)
     *
     * @param inlpBuffer
     * @param incontainsbuff
     * @return
     */
    public static boolean containsIgnoreBlank(String inlpBuffer, String incontainsbuff) {
        String lpBuffer = StringUtil.remove(inlpBuffer, ' ');
        String containsbuff = StringUtil.remove(incontainsbuff, ' ');
        return StringUtil.contains(lpBuffer, containsbuff);
    }

    /**
     * 功能描述:金额字符串转换:单位分转成单元
     *
     * @param o 传入需要转换的金额字符串
     * @return 转换后的金额字符串
     */
    public static String fenToYuan(Object o) {
        if (o == null)
            return "0.00";
        String s = o.toString();
        int len;
        StringBuilder sb = new StringBuilder();
        if (s != null && s.trim().length() > 0 && !"null".equalsIgnoreCase(s)) {
            s = removeZero(s);
            if (s != null && s.trim().length() > 0 && !"null".equalsIgnoreCase(s)) {
                len = s.length();
                int tmp = s.indexOf("-");
                if (tmp >= 0) {
                    if (len == 2) {
                        sb.append("-0.0").append(s.substring(1));
                    } else if (len == 3) {
                        sb.append("-0.").append(s.substring(1));
                    } else {
                        sb.append(s.substring(0, len - 2)).append(".").append(s.substring(len - 2));
                    }
                } else {
                    if (len == 1) {
                        sb.append("0.0").append(s);
                    } else if (len == 2) {
                        sb.append("0.").append(s);
                    } else {
                        sb.append(s.substring(0, len - 2)).append(".").append(s.substring(len - 2));
                    }
                }
            } else {
                sb.append("0.00");
            }
        } else {
            sb.append("0.00");
        }
        return sb.toString();
    }


    /**
     * 功能描述:去除字符串首部为"0"字符
     *
     * @param str 传入需要转换的字符串
     * @return 转换后的字符串
     */
    public static String removeZero(String str) {
        char ch;
        String result = "";
        if (str != null && str.trim().length() > 0 && !"null".equalsIgnoreCase(str.trim())) {
            try {
                for (int i = 0; i < str.length(); i++) {
                    ch = str.charAt(i);
                    if (ch != '0') {
                        result = str.substring(i);
                        break;
                    }
                }
            } catch (Exception e) {
                result = "";
            }
        } else {
            result = "";
        }
        return result;

    }

    /**
     * 判断两个字符串大小
     *
     * @param str1
     * @param str2
     * @return
     */
    public static int compare(String str1, String str2) {
        return str1.compareTo(str2);
    }

    /**
     * 判断两个字符串大小(忽虑字符大小写)
     *
     * @param str1
     * @param str2
     * @return
     */
    public static int compareIgnoreCase(String str1, String str2) {
        return str1.compareToIgnoreCase(str2);
    }

    /**
     * 按指定长度分隔字符串
     *
     * @param str
     * @param length
     * @return
     */
    public static String[] split(String str, int length) {
        int nCount = str.length() / length + 1;
        String retn[] = new String[nCount];
        for (int i = 0; i < nCount; i++) retn[i] = StringUtil.substring(str, length * i, length * (i + 1));
        return retn;
    }

    /**
     * 根据分隔符提取字符串(不忽律空字符)
     *
     * @param str
     * @param splitChar
     * @return
     */
    public static String[] splitNoIgnoreBlank(String str, String splitChar) {
        List ElementLst = new ArrayList();
        int Index1 = -splitChar.length();
        while (Index1 < str.length()) {
            int Index = Index1 + splitChar.length();
            Index1 = StringUtil.indexOf(str, splitChar, Index);
            if (Index1 < 0) Index1 = str.length();
            ElementLst.add(StringUtil.substring(str, Index, Index1));
        }
        return (String[]) ElementLst.toArray(new String[]{});
    }

    /**
     * 将字符串按照指定类型分割
     *
     * @param aITaskExpr
     * @return
     */
    public static String[][] splitExpr(String aITaskExpr) {
        java.util.List aVector = new java.util.ArrayList();
        if (StringUtil.isBlank(aITaskExpr) == false && StringUtil.contains(aITaskExpr, "=")) {
            String aITaskExprL[] = StringUtil.split(aITaskExpr, ";");
            for (int index = 0; index < aITaskExprL.length; index++) {
                String temp[] = StringUtil.split(aITaskExprL[index], "=");
                if (temp != null && temp.length > 0) {
                    aVector.add(new String[]{temp[0], temp.length > 1 ? temp[1] : ""});
                }
            }
        }
        return (String[][]) aVector.toArray(new String[][]{});
    }

    /**
     * 将字符串按照指定类型分割
     *
     * @param aRefeValue
     * @param aITaskExpr
     * @return
     */
    public static String splitExpr(String aRefeValue, String aITaskExpr) {
        String aValue = aITaskExpr;
        String aITaskExprL[][] = StringUtil.splitExpr(aITaskExpr);
        if (aITaskExprL != null && aITaskExprL.length > 0) {
            aValue = null;
            for (int index = 0; index < aITaskExprL.length; index++) {
                if (StringUtil.equals(aITaskExprL[index][0], aRefeValue)) {
                    aValue = aITaskExprL[index][1];
                    break;
                }
            }
        }
        return aValue;
    }

    /**
     * 将指定字符串分割后放入map
     *
     * @param aITaskExpr
     * @param aITaskExprList
     */
    public static void splitExpr(String aITaskExpr, java.util.Map aITaskExprList) {
        String aITaskExprL[][] = StringUtil.splitExpr(aITaskExpr);
        if (aITaskExprL != null && aITaskExprL.length > 0) {
            for (int index = 0; index < aITaskExprL.length; index++)
                aITaskExprList.put(aITaskExprL[index][0], aITaskExprL[index][1]);
        }
    }

    /**
     * 用ch替换字符串中指定位置的字符
     *
     * @param str
     * @param pos
     * @param ch
     */
    public static String replace(String str, int pos, char ch){
        if (str == null || str.getBytes().length <= pos)
            throw new ArrayIndexOutOfBoundsException();
        byte SrcByte[] = str.getBytes();
        SrcByte[pos] = (byte) ch;
        return new String(SrcByte);
    }

    /**
     * 加密
     *
     * @param str
     * @return
     */
    public static String DoEncrypt(String str) {
        int i;
        int tmpch;
        StringBuilder enStrBuff = new StringBuilder();
        for (i = 0; i < str.length(); i++) {
            tmpch = (int) str.charAt(i);
            tmpch = tmpch ^ 0x01;
            tmpch = tmpch ^ 0x0a;
            enStrBuff.append(Integer.toHexString(tmpch));
        }
        return enStrBuff.toString().toUpperCase();
    }

    /**
     * 解密
     *
     * @param str
     * @return
     */
    public static String DoDecrypt(String str) {
        int tmpch;
        String deStr = str.toLowerCase();
        StringBuilder deStrBuff = new StringBuilder();
        for (int i = 0; i < deStr.length(); i += 2) {
            String subStr = deStr.substring(i, i + 2);
            tmpch = Integer.parseInt(subStr, 16);
            tmpch = tmpch ^ 0x01;
            tmpch = tmpch ^ 0x0a;
            deStrBuff.append((char) tmpch);
        }
        return deStrBuff.toString();
    }

    /**
     * 判断是否相同
     *
     * @param str1
     * @param str2
     * @return 是否相同
     */
    public static final boolean isSame(String str1, String str2) {
        if (StringUtil.isBlank(str1) && StringUtil.isBlank(str2)) {
            return true;
        } else if (!StringUtil.isBlank(str1) && !StringUtil.isBlank(str2) && str1.equals(str2)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 判断字符串是否为空或空字符
     *
     * @param str
     * @return 是否为空
     */
    public static final boolean isNull(String str) {
        if (str == null || "".equals(str.trim())) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 字符串通配符算法
     * 1,通配符*号,表示可以匹配任意多个字符
     * 2,通配符问号?表示匹配一个字符
     * 举例:字符串test.txt,通配符为t?s*.txt为true
     *
     * @param pattern
     * @param str
     * @return
     */
    public static final boolean wildcardMatch(String str, String pattern) {
        int patternLength = pattern.length();
        int strLength = str.length();
        int strIndex = 0;
        char ch;
        for (int patternIndex = 0; patternIndex < patternLength; patternIndex++) {
            ch = pattern.charAt(patternIndex);
            if (ch == '*') {
                while (strIndex < strLength) {
                    if (wildcardMatch(str.substring(strIndex), pattern.substring(patternIndex + 1)))
                        return true;
                    strIndex++;
                }
            } else if (ch == '?') {
                strIndex++;
                if (strIndex > strLength)
                    return false;
            } else {
                if ((strIndex >= strLength || (ch != str.charAt(strIndex))))
                    return false;
                strIndex++;
            }
        }
        return (strIndex == strLength);
    }

    /**
     * 取最后一个匹配对象
     *
     * @param aPackage
     * @return
     */
    public static final String wildcardRight(String aPackage, String aMatch) {
        String[] aWildCard = StringUtil.split(aPackage, aMatch);
        return aWildCard[aWildCard.length - 1];
    }

    /**
     * 取第一个匹配对象
     *
     * @param aPackage
     * @return
     */
    public static final String wildcardLeft(String aPackage, String aMatch) {
        StringBuilder aWildCard = new StringBuilder();
        String[] aWildMatch = StringUtil.split(aPackage, aMatch);
        for (int index = 0; index < aWildMatch.length - 1; index++) {
            aWildCard.append(aWildMatch[index]);
            if (index < aWildMatch.length - 2) aWildCard.append(aMatch);
        }
        return aWildCard.toString();
    }

    /**
     * 拼接byte数组
     *
     * @param aBinary 字符串字节
     * @return
     */
    public static final StringBuilder concatBinary(byte[][] aBinary) {
        StringBuilder aStringbin = new StringBuilder();
        for (int index = 0; index < aBinary.length; index++) {
            aStringbin.append(new String(aBinary[index])).append(index != aBinary.length - 1 ? "\n" : "");
        }
        return aStringbin;
    }

    /**
     * 右切位
     *
     * @param len
     * @return
     */
    public static final String trimRight(String str, int len) {
        if (str == null || str.length() < len || len < 0) return str;
        return StringUtil.substring(str, str.length() - len);
    }

    /**
     * 左切位
     * @param str
     * @param len
     * @return
     */
    public static final String trimLeft(String str, int len) {
        if (str == null || str.length() < len || len < 0) return str;
        return StringUtil.substring(str, 0, len);
    }

    /**
     * 抛出异常
     *
     * @param t
     * @param aVM_MAX_BYTE
     * @return
     */
    public static final String doThrowable(Throwable t, int aVM_MAX_BYTE) {
        String aThrowable = null;
        try {
            Throwable tt = t;
            if (tt.getCause() != null) tt = tt.getCause();
            StringWriter aWrite = new StringWriter();
            PrintWriter out = new PrintWriter(aWrite);
            tt.printStackTrace(out);
            out.flush();
            out.close();
            aThrowable = aWrite.toString();
            aWrite.close();
            if (aThrowable.getBytes().length > aVM_MAX_BYTE) {
                aThrowable = StringUtil.substring(aThrowable, 0, aVM_MAX_BYTE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return aThrowable;
    }

    /**
     * 将字符串对象转换成字符串如果是空就用""赋值
     *
     * @param str
     * @return
     */
    public static String getEmptyIfNullObj(Object str) {
        return str == null ? "" : str.toString();
    }

    /**
     * 获取当前年月一般分表使用。例如:202004
     * @return
     */
    public static String getCurMonth() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMM");
        String month = formatter.format(new Date());
        return month;
    }

    // 2011-07-07
    public static String getDiffMonth(String inMonth, int i) {
        int iYear = Integer.parseInt(inMonth.substring(0, 4));
        int iMonth = Integer.parseInt(inMonth.substring(4, 6));
        int iMonthTmp = iMonth + i;
        int m = iMonthTmp % 12; // 月
        int n = iMonthTmp / 12; // 年

        if (m <= 0) {
            n--;
            m += 12;
        }
        String sMonth = m < 10 ? "0" + m : String.valueOf(m);

        return (iYear + n) + sMonth;
    }

    // MD5 加密算法
    public static String MD5(String inStr) {
        MessageDigest md5 = null;

        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            return "";
        }
        char[] charArray = inStr.toCharArray();
        byte[] byteArray = new byte[charArray.length];
        for (int i = 0; i < charArray.length; i++) {
            byteArray[i] = (byte) charArray[i];
        }
        byte[] md5Bytes = md5.digest(byteArray);
        StringBuilder hexValue = new StringBuilder();

        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16)
                hexValue.append("0");
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }

    /**
     * 得到当前时间的interval后的日期,
     * 如今天是2013-6-27,interval为-1时,则返回20130626
     *
     * @param interval
     * @return
     */
    public static String getDiffDay(int interval) {
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        c.add(Calendar.DAY_OF_MONTH, interval);
        return new SimpleDateFormat("yyyyMMdd").format(c.getTime());
    }

    /**
     * 字符串为空转成""
     * @param input
     * @return
     */
    public static final String getEmptyIfNull(String input) {
        return input == null ? "" : input;
    }

    /**
     * 将分转换成元
     *
     * @param pFenValue
     * @return
     */
    public static String convertMoneyValue(long pFenValue) {
        NumberFormat nf = NumberFormat.getInstance();
        nf.setMaximumFractionDigits(2);
        nf.setMinimumFractionDigits(2);
        nf.setGroupingUsed(false);
        return nf.format(pFenValue / 100.00);
    }

    /**
     * 替换html中的标签
     * @param str
     * @return
     */
    public static String replaceHtml(String str) {
        String tmpstr = str;
        tmpstr = replace(tmpstr, "<br>", "\n");
        tmpstr = replace(tmpstr, "&lt;", "<");
        tmpstr = replace(tmpstr, "&gt;", ">");
        tmpstr = replace(tmpstr, "&amp;", "&");
        tmpstr = replace(tmpstr, "&apos;", "\'");
        tmpstr = replace(tmpstr, "&quot;", "\"");
        tmpstr = replace(tmpstr, "&nbsp;", " ");
        return tmpstr;
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/72719.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!