Java常用工具类封装——String操作工具类

来源:互联网 发布:贵金属行情分析软件 编辑:程序博客网 时间:2024/05/21 17:23

项目中经常需要用到String的一些操作,结合看到的一些前人的工具类抽取,编写了如下针对String的常用操作的工具类,供大家参考。

/**   
 * @Copyright © 2017 Sun Info. Tech Ltd. All rights reserved.
 *
 * @Package: com.util.String
 * @author: Hal Sun   
 * @date: 2017-09-03 10:54:13
 */
package com.util.String;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: StringUtil
 * @Description: TODO
 * @author: Hal Sun
 * @date: 2017-09-03 10:54:13
 */
public class StringUtil {
    private static final int INDEX_NOT_FOUND = -1;
    private static final String EMPTY = "";
    /**
     * <p>
     * The maximum size to which the padding constant(s) can expand.
     * </p>
     */
    private static final int PAD_LIMIT = 8192;

    /**
     * 功能:将半角的符号转换成全角符号.(即英文字符转中文字符)
     *
     * @author jiangshuai
     * @param str
     *            源字符串
     * @return String
     * @date 2017年04月24日
     */
    public static String changeToFull(String str) {
        String source = "1234567890!@#$%^&*()abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_=+\\|[];:'\",<.>/?";
        String[] decode = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "!", "@", "#", "$", "%", "︿", "&", "*",
                "(", ")", "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", "-", "_", "=", "+", "\", "|", "【", "】", ";",
                ":", "'", "\"", ",", "〈", "。", "〉", "/", "?" };
        String result = "";
        for (int i = 0; i < str.length(); i++) {
            int pos = source.indexOf(str.charAt(i));
            if (pos != -1) {
                result += decode[pos];
            } else {
                result += str.charAt(i);
            }
        }
        return result;
    }

    /**
     * <p>
     * 进行tostring操作,如果传入的是null,返回空字符串。
     * </p>
     *
     * <pre>
     *   
     * ObjectUtils.toString(null)         = ""  
     * ObjectUtils.toString("")           = ""  
     * ObjectUtils.toString("bat")        = "bat"  
     * ObjectUtils.toString(Boolean.TRUE) = "true"
     * </pre>
     *
     * @param obj
     *            源
     * @return String
     */
    public static String toString(Object obj) {
        return obj == null ? "" : obj.toString();
    }

    /**
     * <p>
     * 进行tostring操作,如果传入的是null,返回指定的默认值。
     * </p>
     *
     * <pre>
     *   
     * ObjectUtils.toString(null, null)           = null  
     * ObjectUtils.toString(null, "null")         = "null"  
     * ObjectUtils.toString("", "null")           = ""  
     * ObjectUtils.toString("bat", "null")        = "bat"  
     * ObjectUtils.toString(Boolean.TRUE, "null") = "true"
     * </pre>
     *
     * @param obj
     *            源
     * @param nullStr
     *            如果obj为null时返回这个指定值
     * @return String
     */
    public static String toString(Object obj, String nullStr) {
        return obj == null ? nullStr : obj.toString();
    }

    /**
     * <p>
     * 只从源字符串中移除指定开头子字符串.
     * </p>
     *
     * <pre>
     *   
     * StringUtil.removeStart(null, *)      = null  
     * StringUtil.removeStart("", *)        = ""  
     * StringUtil.removeStart(*, null)      = *  
     * StringUtil.removeStart("www.domain.com", "www.")   = "domain.com"  
     * StringUtil.removeStart("domain.com", "www.")       = "domain.com"  
     * StringUtil.removeStart("www.domain.com", "domain") = "www.domain.com"  
     * StringUtil.removeStart("abc", "")    = "abc"
     * </pre>
     *
     * @param str
     *            源字符串
     * @param remove
     *            将要被移除的子字符串
     * @return String
     */
    public static String removeStart(String str, String remove) {
        if (isEmpty(str) || isEmpty(remove)) {
            return str;
        }
        if (str.startsWith(remove)) {
            return str.substring(remove.length());
        }
        return str;
    }

    /**
     * <p>
     * 只从源字符串中移除指定结尾的子字符串.
     * </p>
     *
     * <pre>
     *   
     * StringUtil.removeEnd(null, *)      = null  
     * StringUtil.removeEnd("", *)        = ""  
     * StringUtil.removeEnd(*, null)      = *  
     * StringUtil.removeEnd("www.domain.com", ".com.")  = "www.domain.com"  
     * StringUtil.removeEnd("www.domain.com", ".com")   = "www.domain"  
     * StringUtil.removeEnd("www.domain.com", "domain") = "www.domain.com"  
     * StringUtil.removeEnd("abc", "")    = "abc"
     * </pre>
     *
     * @param str
     *            源字符串
     * @param remove
     *            将要被移除的子字符串
     * @return String
     */
    public static String removeEnd(String str, String remove) {
        if (isEmpty(str) || isEmpty(remove)) {
            return str;
        }
        if (str.endsWith(remove)) {
            return str.substring(0, str.length() - remove.length());
        }
        return str;
    }

    /**
     * <p>
     * 将一个字符串重复N次
     * </p>
     *
     * <pre>
     *   
     * StringUtil.repeat(null, 2) = null  
     * StringUtil.repeat("", 0)   = ""  
     * StringUtil.repeat("", 2)   = ""  
     * StringUtil.repeat("a", 3)  = "aaa"  
     * StringUtil.repeat("ab", 2) = "abab"  
     * StringUtil.repeat("a", -2) = ""
     * </pre>
     *
     * @param str
     *            源字符串
     * @param repeat
     *            重复的次数
     * @return String
     */
    public static String repeat(String str, int repeat) {
        // Performance tuned for 2.0 (JDK1.4)

        if (str == null) {
            return null;
        }
        if (repeat <= 0) {
            return EMPTY;
        }
        int inputLength = str.length();
        if (repeat == 1 || inputLength == 0) {
            return str;
        }
        if (inputLength == 1 && repeat <= PAD_LIMIT) {
            return repeat(str.charAt(0), repeat);
        }

        int outputLength = inputLength * repeat;
        switch (inputLength) {
        case 1:
            return repeat(str.charAt(0), repeat);
        case 2:
            char ch0 = str.charAt(0);
            char ch1 = str.charAt(1);
            char[] output2 = new char[outputLength];
            for (int i = repeat * 2 - 2; i >= 0; i--, i--) {
                output2[i] = ch0;
                output2[i + 1] = ch1;
            }
            return new String(output2);
        default:
            StringBuilder buf = new StringBuilder(outputLength);
            for (int i = 0; i < repeat; i++) {
                buf.append(str);
            }
            return buf.toString();
        }
    }

    /**
     * <p>
     * 将一个字符串重复N次,并且中间加上指定的分隔符
     * </p>
     *
     * <pre>
     *   
     * StringUtil.repeat(null, null, 2) = null  
     * StringUtil.repeat(null, "x", 2)  = null  
     * StringUtil.repeat("", null, 0)   = ""  
     * StringUtil.repeat("", "", 2)     = ""  
     * StringUtil.repeat("", "x", 3)    = "xxx"  
     * StringUtil.repeat("?", ", ", 3)  = "?, ?, ?"
     * </pre>
     *
     * @param str
     *            源字符串
     * @param separator
     *            分隔符
     * @param repeat
     *            重复次数
     * @return String
     */
    public static String repeat(String str, String separator, int repeat) {
        if (str == null || separator == null) {
            return repeat(str, repeat);
        } else {
            // given that repeat(String, int) is quite optimized, better to rely
            // on it than try and splice this into it
            String result = repeat(str + separator, repeat);
            return removeEnd(result, separator);
        }
    }

    /**
     * <p>
     * 将某个字符重复N次.
     * </p>
     *
     * @param ch
     *            某个字符
     * @param repeat
     *            重复次数
     * @return String
     */
    public static String repeat(char ch, int repeat) {
        char[] buf = new char[repeat];
        for (int i = repeat - 1; i >= 0; i--) {
            buf[i] = ch;
        }
        return new String(buf);
    }

    /**
     * <p>
     * 字符串长度达不到指定长度时,在字符串右边补指定的字符.
     * </p>
     *
     * <pre>
     *   
     * StringUtil.rightPad(null, *, *)     = null  
     * StringUtil.rightPad("", 3, 'z')     = "zzz"  
     * StringUtil.rightPad("bat", 3, 'z')  = "bat"  
     * StringUtil.rightPad("bat", 5, 'z')  = "batzz"  
     * StringUtil.rightPad("bat", 1, 'z')  = "bat"  
     * StringUtil.rightPad("bat", -1, 'z') = "bat"
     * </pre>
     *
     * @param str
     *            源字符串
     * @param size
     *            指定的长度
     * @param padChar
     *            进行补充的字符
     * @return String
     */
    public static String rightPad(String str, int size, char padChar) {
        if (str == null) {
            return null;
        }
        int pads = size - str.length();
        if (pads <= 0) {
            return str; // returns original String when possible
        }
        if (pads > PAD_LIMIT) {
            return rightPad(str, size, String.valueOf(padChar));
        }
        return str.concat(repeat(padChar, pads));
    }

    /**
     * <p>
     * 扩大字符串长度,从左边补充指定字符
     * </p>
     *
     * <pre>
     *   
     * StringUtil.rightPad(null, *, *)      = null  
     * StringUtil.rightPad("", 3, "z")      = "zzz"  
     * StringUtil.rightPad("bat", 3, "yz")  = "bat"  
     * StringUtil.rightPad("bat", 5, "yz")  = "batyz"  
     * StringUtil.rightPad("bat", 8, "yz")  = "batyzyzy"  
     * StringUtil.rightPad("bat", 1, "yz")  = "bat"  
     * StringUtil.rightPad("bat", -1, "yz") = "bat"  
     * StringUtil.rightPad("bat", 5, null)  = "bat  "  
     * StringUtil.rightPad("bat", 5, "")    = "bat  "
     * </pre>
     *
     * @param str
     *            源字符串
     * @param size
     *            扩大后的长度
     * @param padStr
     *            在右边补充的字符串
     * @return String
     */
    public static String rightPad(String str, int size, String padStr) {
        if (str == null) {
            return null;
        }
        if (isEmpty(padStr)) {
            padStr = " ";
        }
        int padLen = padStr.length();
        int strLen = str.length();
        int pads = size - strLen;
        if (pads <= 0) {
            return str; // returns original String when possible
        }
        if (padLen == 1 && pads <= PAD_LIMIT) {
            return rightPad(str, size, padStr.charAt(0));
        }

        if (pads == padLen) {
            return str.concat(padStr);
        } else if (pads < padLen) {
            return str.concat(padStr.substring(0, pads));
        } else {
            char[] padding = new char[pads];
            char[] padChars = padStr.toCharArray();
            for (int i = 0; i < pads; i++) {
                padding[i] = padChars[i % padLen];
            }
            return str.concat(new String(padding));
        }
    }

    /**
     * <p>
     * 检查字符串是否全部为小写.
     * </p>
     *
     * <pre>
     *   
     * StringUtil.isAllLowerCase(null)   = false  
     * StringUtil.isAllLowerCase("")     = false  
     * StringUtil.isAllLowerCase("  ")   = false  
     * StringUtil.isAllLowerCase("abc")  = true  
     * StringUtil.isAllLowerCase("abC") = false
     * </pre>
     *
     * @param cs
     *            源字符串
     * @return String
     */
    public static boolean isAllLowerCase(String cs) {
        if (cs == null || isEmpty(cs)) {
            return false;
        }
        int sz = cs.length();
        for (int i = 0; i < sz; i++) {
            if (Character.isLowerCase(cs.charAt(i)) == false) {
                return false;
            }
        }
        return true;
    }

    /**
     * <p>
     * 检查是否都是大写.
     * </p>
     *
     * <pre>
     *   
     * StringUtil.isAllUpperCase(null)   = false  
     * StringUtil.isAllUpperCase("")     = false  
     * StringUtil.isAllUpperCase("  ")   = false  
     * StringUtil.isAllUpperCase("ABC")  = true  
     * StringUtil.isAllUpperCase("aBC") = false
     * </pre>
     *
     * @param cs
     *            源字符串
     * @return String
     */
    public static boolean isAllUpperCase(String cs) {
        if (cs == null || StringUtil.isEmpty(cs)) {
            return false;
        }
        int sz = cs.length();
        for (int i = 0; i < sz; i++) {
            if (Character.isUpperCase(cs.charAt(i)) == false) {
                return false;
            }
        }
        return true;
    }

    /**
     * <p>
     * 反转字符串.
     * </p>
     *
     * <pre>
     *   
     * StringUtil.reverse(null)  = null  
     * StringUtil.reverse("")    = ""  
     * StringUtil.reverse("bat") = "tab"
     * </pre>
     *
     * @param str
     *            源字符串
     * @return String
     */
    public static String reverse(String str) {
        if (str == null) {
            return null;
        }
        return new StringBuilder(str).reverse().toString();
    }

    /**
     * <p>
     * 字符串达不到一定长度时在右边补空白.
     * </p>
     *
     * <pre>
     *   
     * StringUtil.rightPad(null, *)   = null  
     * StringUtil.rightPad("", 3)     = "   "  
     * StringUtil.rightPad("bat", 3)  = "bat"  
     * StringUtil.rightPad("bat", 5)  = "bat  "  
     * StringUtil.rightPad("bat", 1)  = "bat"  
     * StringUtil.rightPad("bat", -1) = "bat"
     * </pre>
     *
     * @param str
     *            源字符串
     * @param size
     *            指定的长度
     * @return String
     */
    public static String rightPad(String str, int size) {
        return rightPad(str, size, ' ');
    }

    /**
     * <p>
     * 截取一个字符串的前几个.
     * </p>
     *
     * <pre>
     *   
     * StringUtil.left(null, *)    = null  
     * StringUtil.left(*, -ve)     = ""  
     * StringUtil.left("", *)      = ""  
     * StringUtil.left("abc", 0)   = ""  
     * StringUtil.left("abc", 2)   = "ab"  
     * StringUtil.left("abc", 4)   = "abc"
     * </pre>
     *
     * @param str
     *            源字符串
     * @param len
     *            截取的长度
     * @return the String
     */
    public static String left(String str, int len) {
        if (str == null) {
            return null;
        }
        if (len < 0) {
            return EMPTY;
        }
        if (str.length() <= len) {
            return str;
        }
        return str.substring(0, len);
    }

    /**
     * 功能:切换字符串中的所有字母大小写。<br/>
     *
     * <pre>
     *   
     * StringUtil.swapCase(null)                 = null  
     * StringUtil.swapCase("")                   = ""  
     * StringUtil.swapCase("The dog has a BONE") = "tHE DOG HAS A bone"
     * </pre>
     *
     *
     * @param str
     *            源字符串
     * @return String
     */
    public static String swapCase(String str) {
        if (StringUtil.isEmpty(str)) {
            return str;
        }
        char[] buffer = str.toCharArray();

        boolean whitespace = true;

        for (int i = 0; i < buffer.length; i++) {
            char ch = buffer[i];
            if (Character.isUpperCase(ch)) {
                buffer[i] = Character.toLowerCase(ch);
                whitespace = false;
            } else if (Character.isTitleCase(ch)) {
                buffer[i] = Character.toLowerCase(ch);
                whitespace = false;
            } else if (Character.isLowerCase(ch)) {
                if (whitespace) {
                    buffer[i] = Character.toTitleCase(ch);
                    whitespace = false;
                } else {
                    buffer[i] = Character.toUpperCase(ch);
                }
            } else {
                whitespace = Character.isWhitespace(ch);
            }
        }
        return new String(buffer);
    }
    
    /**
     *
    * @Title: convertString  
    * @Description: 将首字母变成大写  
    * @param str
    * @param beginUp
    * @return String
    * @throws
     */

    private String convertString(String str, Boolean beginUp) {

        char[] ch = str.toCharArray();
        StringBuffer sbf = new StringBuffer();
        for (int i = 0; i < ch.length; i++) {
            if (i == 0 && beginUp) {// 如果首字母需大写
                sbf.append(charToUpperCase(ch[i]));
            } else {
                sbf.append(charToLowerCase(ch[i]));
            }
        }
        return sbf.toString();
    }

    /** 转大写 **/
    private char charToUpperCase(char ch) {
        if (ch <= 122 && ch >= 97) {
            ch -= 32;
        }
        return ch;
    }

    /*** 转小写 **/
    private char charToLowerCase(char ch) {
        if (ch <= 90 && ch >= 65) {
            ch += 32;
        }
        return ch;
    }

    /**
     * 功能:检查这个字符串是不是空字符串。<br/>
     * 如果这个字符串为null或者trim后为空字符串则返回true,否则返回false。
     *
     * @author Hal Sun
     * @date 2017年04月24日
     * @param chkStr
     *            被检查的字符串
     * @return boolean
     */
    public static boolean isEmpty(String chkStr) {
        if (chkStr == null) {
            return true;
        } else {
            return "".equals(chkStr.trim()) ? true : false;
        }
    }
}


阅读全文
0 0