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

猜你喜欢

转载自www.cnblogs.com/qq931399960/p/10697895.html