commons-lang3之StringUtils


字符串是一種在開發中經常使用到的數據類型,對字符串的處理也變得非常重要,字符串本身有一些方法,但都沒有對null做處理,而且有時可能還需要做一些額外處理才能滿足我們的需求,比如,要判斷某個字符串中是否包含字符串a或者字符串ax,使用自帶的字符串方法,我們可能要這么寫

boolean isContains = false;
String s = "abc";
if(s != null) {
    if(s.contains("a") || s.contains("ax")) {
        isContains = true;
        }
}

使用commons-lang3工具包,就只需要一行代碼就可以,其他內容已經被封裝好,並且已經對null做了處理,StringUtils類中大部分的方法都對null做了處理,所以不會出現空指針異常

boolean flag = StringUtils.containsAny("abc", new String[] {"a","ax"});

但即便如此,對於第三方jar包,也建議不要直接使用,最好自己封裝一下,使用時調用自己封裝的接口,這樣,以后如果方法有變動,或者使用其他的jar包,也不需要每個調用都做修改,只需要修改自己封裝的接口即可。不要使用已過期的方法

maven依賴如:https://www.cnblogs.com/qq931399960/p/10689571.html中所示,可以簡單先看下這個類中的方法,有個印象,在對字符串做處理時,再去源碼中查看具體的使用方式,每個方法在注釋中都有詳細的例子,使用起來很方便,比如上述containsAny方法

    /**
     * <p>Checks if the CharSequence contains any of the CharSequences in the given array.</p>
     *
     * <p>
     * A {@code null} {@code cs} CharSequence will return {@code false}. A {@code null} or zero
     * length search array will return {@code false}.
     * </p>
     *
     * <pre>
     * StringUtils.containsAny(null, *)            = false
     * StringUtils.containsAny("", *)              = false
     * StringUtils.containsAny(*, null)            = false
     * StringUtils.containsAny(*, [])              = false
     * StringUtils.containsAny("abcd", "ab", null) = true
     * StringUtils.containsAny("abcd", "ab", "cd") = true
     * StringUtils.containsAny("abc", "d", "abc")  = true
     * </pre>
     *
     *
     * @param cs The CharSequence to check, may be null
     * @param searchCharSequences The array of CharSequences to search for, may be null.
     * Individual CharSequences may be null as well.
     * @return {@code true} if any of the search CharSequences are found, {@code false} otherwise
     * @since 3.4
     */
    public static boolean containsAny(final CharSequence cs, final CharSequence... searchCharSequences) {
        if (isEmpty(cs) || ArrayUtils.isEmpty(searchCharSequences)) {
            return false;
        }
        for (final CharSequence searchCharSequence : searchCharSequences) {
            if (contains(cs, searchCharSequence)) {
                return true;
            }
        }
        return false;
    }

下面是對StringUtils的一些簡單測試

        // true,為null或者size==0,返回true
        boolean empty = StringUtils.isEmpty("");
        // false,與isEmpty相反
        boolean notEmpty = StringUtils.isNotEmpty("");
        // true,數組中有一個為null或size==0的字符串,則返回true
        boolean anyEmpty = StringUtils.isAnyEmpty(new String[] { "aa", "" });
        // false,全部都不為空,返回true
        boolean noneEmpty = StringUtils.isNoneEmpty(new String[] { "", "aa" });
        // true,全部為空,返回true
        boolean allEmpty = StringUtils.isAllEmpty(new String[] { "", "" });

        // true,為null或者size==0或者只存在空白字符(如" "),則返回true
        boolean blank = StringUtils.isBlank(" ");
        // false,與isBlank相反
        boolean notBlank = StringUtils.isNotBlank(" ");
        // true,數組中任何一個為null或者空字符串或者空白字符,則返回true
        boolean anyBlank = StringUtils.isAnyBlank(new String[] { "dd", " " });
        // false,與isAnyBlank 相反
        boolean noneBlank = StringUtils.isNoneBlank(new String[] { "dd", "" });
        // true,數組中的數據全部為null,或者空字符串或者空白字符,則返回true
        boolean allBlank = StringUtils.isAllBlank(new String[] { "", " " });

        // dd,去掉前后字符,為null,返回null
        String trim = StringUtils.trim(" dd ");
        // "",為null或者size==0,則返回空字符串
        String trimToEmpty = StringUtils.trimToEmpty(" ");
        // null,為null或者size==0,則返回null
        String trimToNull = StringUtils.trimToNull(" ");

        // abc,截取字符串
        String truncate = StringUtils.truncate("abcde", 3);
        // cdefg,從第二個起,截取5個長度
        String truncate = StringUtils.truncate("abcdefghl", 2, 5);
        // ddds與trim類似
        String strip = StringUtils.strip(" dd d s ");
        // yes, it is,去掉指定的開頭字符和結尾字符,第二個字符為dd或者da也會有同樣輸出
        String strip = StringUtils.strip("ddyes, it is ddd", "d");
        // yes, it is ddd
        String stripStart = StringUtils.stripStart("ddyes, it is ddd", "d");
        // ddyes, it is
        String stripEnd = StringUtils.stripEnd("ddyes, it is ddd", "d");
        // [it is, dd],去掉參數中所有元素的前后空格
        String[] stripAll = StringUtils.stripAll(" it is ", " dd ");
        // [it is , it],去掉數組中每個元素前后的指定字符
        String[] stripAll = StringUtils.stripAll(new String[] { "ddit is d", "ditd" }, "d");
        // false
        boolean equals = StringUtils.equals(null, "");
        // true
        boolean equalsIgnoreCase = StringUtils.equalsIgnoreCase("abc", "ABC");
        // [,ab,cde, dsd,] 2個元素,默認分隔符為空白字符
        String[] split = StringUtils.split(",ab,cde dsd,");
        // [ab, cde , dsd] 3個元素,去掉了為空的元素,空白字符組成的字符串會保留
        String[] split = StringUtils.split(",ab,cde ,,dsd,", ",");
        // [ab, cde, dsd] 3個元素,以,和空白字符分隔,第二個參數中每個字符都當成一個分隔符,與上一個方法比,放方法第二個元素后沒有空白字符
        String[] split = StringUtils.split(",ab,cde ,,dsd,", ", ");
        // [ab, cde ,,dsd,] 2個元素,由於最大只允許2個
        String[] split = StringUtils.split(",ab,cde ,,dsd,", ", ", 2);
        // [,ab,cde , ,dsd,] 2個元素,第二個參數所有字符當成一個整體的分隔符
        String[] splitByWholeSeparator = StringUtils.splitByWholeSeparator(",ab,cde , ,dsd,", ", ");
        // [, dd, ],3個元素,兩個空的
        String[] splitPreserveAllTokens = StringUtils.splitPreserveAllTokens(" dd ");
        // [, aa, , ],4個元素,3個空的
        String[] splitPreserveAllTokens = StringUtils.splitPreserveAllTokens(",aa,,", ",");
        // [, aa, , bb, ] 5個元素,以,或者空白字符分隔
        String[] splitPreserveAllTokens = StringUtils.splitPreserveAllTokens(",aa, bb,", ", ");
        // [,aa, bb,] 2個,以, 作為一個整體分隔
        String[] splitByWholeSeparatorPreserveAllTokens = StringUtils.splitByWholeSeparatorPreserveAllTokens(",aa, bb,",
                ", ");
        // [ABC, 123, abc, ;,., I, t] 6個元素
        String[] splitByCharacterType = StringUtils.splitByCharacterType("ABC123abc;,.It");

        String join = StringUtils.join("12", "a", "df", "3"); // 12adf3
        List<String> ls = new ArrayList<>();
        ls.add("aa");
        ls.add("bb");
        ls.add("cc");
        // insert into table values ('aa','bb','cc');,在組織'aa','bb','cc'
        String join = "'" + StringUtils.join(ls, "','") + "'";
        // abc
        String deleteWhitespace = StringUtils.deleteWhitespace(" a b c ");
        // abc is it
        String remove = StringUtils.remove("abcdd is dddit", "d");
        // dit isdd,只刪除第一個參數起始處中對應的第二個參數。
        String removeStart = StringUtils.removeStart("ddit isdd", "d");
        // ddit isd, 只刪除第一個參數結束處中對應的第二個參數。
        String removeEnd = StringUtils.removeEnd("ddit isdd", "d");
        // it is
        String removeIgnoreCase = StringUtils.removeIgnoreCase("ddit isdd", "D");
        // rdit
        // isdd,雖然replace的功能已經包含有replaceOne,但如果確定只有一個需要替換,最好還是使用replaceOne,因為這個找到一個替換后就會停止查找
        String replaceOnce = StringUtils.replaceOnce("ddit isdd", "d", "r");
        // rdit isdd
        String replaceOnceIgnoreCase = StringUtils.replaceOnceIgnoreCase("ddit isdd", "D", "r");
        // rrit isrr
        String replace = StringUtils.replace("ddit isdd", "d", "r");
        // rrit isrr
        String replaceIgnoreCase = StringUtils.replaceIgnoreCase("ddit isdd", "D", "r");
        // rris isrr,批量替換
        String replaceEach = StringUtils.replaceEach("ddit isdd", new String[] { "d", "t" }, new String[] { "r", "s" });
        // tcte
        String replaceEachRepeatedly = StringUtils.replaceEachRepeatedly("abcde", new String[] { "ab", "d" },
                new String[] { "d", "t" });
        // aaaaaa 將第一個參數重復第二個參數次,形成一個新的字符串
        String repeat = StringUtils.repeat("aa", 3);
        // aa,aa,aa 將第一個參數重復第三個參數次,並且以第二個參數分隔,形成一個新的字符串
        String repeat = StringUtils.repeat("aa", ",", 3);
        // ab,在左側填充兩個空白字符,形成一個4個字符的字符串,
        String leftPad = StringUtils.leftPad("ab", 4);
        // ab ,在兩邊填充空白字符,形成一個以第一個參數為中心的4個字符串長度字符串
        String center = StringUtils.center("ab", 4);
        // true,正整數返回true
        boolean numeric = StringUtils.isNumeric("123");
        // true 正整數,且包含有空白字符或者空字符串,空白字符,返回true
        boolean numericSpace = StringUtils.isNumericSpace("12 3");
        // 5417543010,獲取字符串中的數字,並拼接在一起
        String digits = StringUtils.getDigits("(541) 754-3010");
        // true,字符串size==0或者空白字符,返回true,null及其他字符返回false
        boolean whitespace = StringUtils.isWhitespace(" ");
        // abcdefg...,顯示指定長度的字符串,多余的使用...
        String abbreviate = StringUtils.abbreviate("abcdefghijklmnopq", 10);
        // abcdefg***
        String abbreviate = StringUtils.abbreviate("abcdefghijklmnopq", "***", 10);
        // abcd***opq
        String abbreviateMiddle = StringUtils.abbreviateMiddle("abcdefghijklmnopq", "***", 10);
        // a,獲取數組共所有元素相同的前綴
        String commonPrefix = StringUtils.getCommonPrefix("abcdf", "ads", "arf");
        // true, endsWith同理
        boolean startsWith = StringUtils.startsWith("abcdef", "ab");
        // true,endsWithIgnoreCase同理
        boolean startsWithIgnoreCase = StringUtils.startsWithIgnoreCase("abcdefg", "aB");
        // true,第一個參數的前綴匹配第二個數組參數中的任何一個元素時,返回true,endsWithAny同理
        boolean startsWithAny = StringUtils.startsWithAny("abcdef", new String[] { "x", "ab", " " });
        // abcxyzddd,如果出第一個參數的后綴包含在后面參數中,則直接返回第一個參數,否則將返回第一個參數+第二個參數
        String appendIfMissing = StringUtils.appendIfMissing("abcxyz", "ddd", new String[] { "qwe", "123" });
        // dddabcxyz,原理同上
        String prependIfMissing = StringUtils.prependIfMissing("abcxyz", "ddd", new String[] { "qwe", "123" });
        // cbd
        String encodedString = StringUtils.toEncodedString(new byte[] { 'c', 'b', 'd' }, Charset.defaultCharset());
        // "xxx"
        String wrap = StringUtils.wrap("xxx", "\"");
        // *xx*
        String wrapIfMissing = StringUtils.wrapIfMissing("xx", "*");
        // 前后必須有相同字符才可以unwrap
        String unwrap = StringUtils.unwrap("'aa'", "'");
        // {97,98,99}
        int[] codePoints = StringUtils.toCodePoints("abc");
        // abc,刪除最后一個字符,如果是\r\n則一起刪除
        String chop = StringUtils.chop("abc\r\n");
        // abc,如果最后存在換行符,則刪除最后的換行符
        String chomp = StringUtils.chomp("abc\r\n");
        // true
        boolean contains = StringUtils.contains("abcd", "ab");
        // true
        boolean containsAny = StringUtils.containsAny("abcdefg", "2", "a");
        // false
        boolean containsOnly = StringUtils.containsOnly("abcdefg", "aa");
        // true
        boolean containsIgnoreCase = StringUtils.containsIgnoreCase("abcdef", "aB");
        // false
        boolean containsNone = StringUtils.containsNone("abcdef", 'a', 'x');
        // true
        boolean containsWhitespace = StringUtils.containsWhitespace("aa bbc");

        // 此外還有substring,indexof等方法
    
View Code

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM