CommonLang3中的StringUtils的Api源码解读

前言

这个包其实我们在平时开发使用的是很频繁的,但是很多时候都没自己从源码的解读下。
刚好这段时间有点时间,我就去搞下。

1 StringUtils方法介绍

StringUtils是提供字符串操作的工具类。提供的方法很多,我们就常见的方法看下。

1.1 isEmpty

StringUtils源码

 public static boolean isEmpty(CharSequence cs) {
        return cs == null || cs.length() == 0;
    }

说明

如果参数str为NULL或者str.length() == 0 返回true

String源码

 public boolean isEmpty() {
        return value.length == 0;
    }
 public int length() {
        return value.length;
    }

说明

此方法通过判断字符串的length是否等于0来进行判断

Demo

  // StringUtils
        System.out.println(StringUtils.isEmpty(""));
        System.out.println(StringUtils.isEmpty(null));
        System.out.println(StringUtils.isEmpty("  "));
        System.out.println(StringUtils.isEmpty("aaaa"));

1.2 isNotEmpty

源码

 public static boolean isNotEmpty(CharSequence cs) {
        return !isEmpty(cs);
    }

说明

这个方法就是isEmpty() 方法取反

Demo

 // StringUtils
        System.out.println(StringUtils.isNotEmpty(""));
        System.out.println(StringUtils.isNotEmpty(null));
        System.out.println(StringUtils.isNotEmpty("  "));
        System.out.println(StringUtils.isNotEmpty("aaaa"));

1.3 isBlank

源码

public static boolean isBlank(CharSequence cs) {
        int strLen = length(cs);
        if (strLen == 0) {
            return true;
        } else {
            for(int i = 0; i < strLen; ++i) {
                if (!Character.isWhitespace(cs.charAt(i))) {
                    return false;
                }
            }

            return true;
        }
    }

说明

如果参数str为NULL或者其长度等于0,又或者其由空格组成,那么此方法都返回true。

Demo

 // StringUtils
        System.out.println(StringUtils.isBlank(""));
        System.out.println(StringUtils.isBlank(null));
        System.out.println(StringUtils.isBlank("  "));
        System.out.println(StringUtils.isBlank("aaaa"));

1.4 isNotBlank

源码·

public static boolean isNotBlank(CharSequence cs) {
        return !isBlank(cs);
    }

说明

这个方法就是isBlank() 方法取反

Demo

// StringUtils
        System.out.println(StringUtils.isNotBlank(""));
        System.out.println(StringUtils.isNotBlank(null));
        System.out.println(StringUtils.isNotBlank("  "));
        System.out.println(StringUtils.isNotBlank("aaaa"));

1.5 trim

源码

// StringUtils
  public static String trim(String str) {
        return str == null ? null : str.trim();
    }

    public static String trimToEmpty(String str) {
        return str == null ? "" : str.trim();
    }

    public static String trimToNull(String str) {
        String ts = trim(str);
        return isEmpty(ts) ? null : ts;
    }

说明

其实还是调用了String的方法trim(),在里面3元运算符 设定默认值。

Demo

System.out.println(StringUtils.trim(null));       
//去空格,将Null和"" 转换为Null                            
System.out.println(StringUtils.trimToNull(""));   
System.out.println(StringUtils.trimToNull(null)); 
// 去空格,将NULL 和 "" 转换为""                           
System.out.println(StringUtils.trimToEmpty(""));  
System.out.println(StringUtils.trimToEmpty(null));

1.6 stripStart

源码

public static String stripStart(String str, String stripChars) {
        int strLen = length(str);
        if (strLen == 0) {
            return str;
        } else {
            int start = 0;
            if (stripChars == null) {
                while(start != strLen && Character.isWhitespace(str.charAt(start))) {
                    ++start;
                }
            } else {
                if (stripChars.isEmpty()) {
                    return str;
                }

                while(start != strLen && stripChars.indexOf(str.charAt(start)) != -1) {
                    ++start;
                }
            }

            return str.substring(start);
        }
    }

说明

去掉str前端的在stripChars中的字符
如果第二个参数为null只去前面空格(否则去掉字符串前面一样的字符,到不一样为止)

Demo

System.out.println(StringUtils.stripStart("ddddsuduu ", "d"));

1.7 stripEnd

源码

 public static String stripEnd(String str, String stripChars) {
        int end = length(str);
        if (end == 0) {
            return str;
        } else {
            if (stripChars == null) {
                while(end != 0 && Character.isWhitespace(str.charAt(end - 1))) {
                    --end;
                }
            } else {
                if (stripChars.isEmpty()) {
                    return str;
                }

                while(end != 0 && stripChars.indexOf(str.charAt(end - 1)) != -1) {
                    --end;
                }
            }

            return str.substring(0, end);
        }
    }

说明

去掉str末端的在stripChars中的字符
如果第二个参数为null只去后面空格,(否则去掉字符串后面一样的字符,到不一样为止)
如果第二个参数为null去空格(否则去掉字符串2边一样的字符,到不一样为止)

Demo

 System.out.println(StringUtils.stripEnd("dabads", "das"));
 System.out.println(StringUtils.strip("fsfsdf", "f"));

1.8 contains

源码

 public static boolean contains(CharSequence seq, CharSequence searchSeq) {
        if (seq != null && searchSeq != null) {
            return CharSequenceUtils.indexOf(seq, searchSeq, 0) >= 0;
        } else {
            return false;
        }
    }
  /***************************************/
   public static boolean containsIgnoreCase(CharSequence str, CharSequence searchStr) {
        if (str != null && searchStr != null) {
            int len = searchStr.length();
            int max = str.length() - len;

            for(int i = 0; i <= max; ++i) {
                if (CharSequenceUtils.regionMatches(str, true, i, searchStr, 0, len)) {
                    return true;
                }
            }

            return false;
        } else {
            return false;
        }
    }
   /***************************************/
    public static boolean containsWhitespace(CharSequence seq) {
        if (isEmpty(seq)) {
            return false;
        } else {
            int strLen = seq.length();

            for(int i = 0; i < strLen; ++i) {
                if (Character.isWhitespace(seq.charAt(i))) {
                    return true;
                }
            }

            return false;
        }
    }

说明

contains 检查是否查到,返回boolean,null返回假
containsIgnoreCase 检查是否查到,返回boolean,null返回假,不区分大小写
containsWhitespace 检查是否有含有空格,返回boolean

Demo

System.out.println(StringUtils.contains("sdf", "dg"));
System.out.println(StringUtils.containsIgnoreCase("sdf", "D"));
System.out.println(StringUtils.containsWhitespace(" d"));

1.9 ordinalIndexOf

源码

  private static int ordinalIndexOf(CharSequence str, CharSequence searchStr, int ordinal, boolean lastIndex) {
        if (str != null && searchStr != null && ordinal > 0) {
            if (searchStr.length() == 0) {
                return lastIndex ? str.length() : 0;
            } else {
                int found = 0;
                int index = lastIndex ? str.length() : -1;

                do {
                    if (lastIndex) {
                        index = CharSequenceUtils.lastIndexOf(str, searchStr, index - 1);
                    } else {
                        index = CharSequenceUtils.indexOf(str, searchStr, index + 1);
                    }

                    if (index < 0) {
                        return index;
                    }

                    ++found;
                } while(found < ordinal);

                return index;
            }
        } else {
            return -1;
        }
    }

说明

返回字符串search在字符串str中第ordinal次出现的位置
如果str=null或searchStr=null或ordinal<=0则返回-1

Demo

 System.out.println(StringUtils.indexOf("akfekcd中华", "k", 2));
 System.out.println(StringUtils.ordinalIndexOf("akfekcd中华", "k", 2));

1.10 defaultIfEmpty

源码

  public static <T extends CharSequence> T defaultIfEmpty(T str, T defaultStr) {
        return isEmpty(str) ? defaultStr : str;
    }

说明

如果字符串为""或者 null 则替换成参数2中的字符串

Demo

        System.out.println("1: " + StringUtils.defaultIfEmpty("", "a"));
        System.out.println("2: " + StringUtils.defaultIfEmpty("\n\t", "a"));
        System.out.println("3: " + StringUtils.defaultIfEmpty("", "a"));
        System.out.println("4: " + StringUtils.defaultIfEmpty("   ", "a"));
        System.out.println("5: " + StringUtils.defaultIfEmpty("aaa", "a"));
        System.out.println("6: " + StringUtils.defaultIfEmpty(" aaa ", "a"));
        System.out.println("7: " + StringUtils.defaultIfEmpty(null, "a"));

1.11 defaultString

源码

 public static String defaultString(String str) {
        return defaultString(str, "");
    }

    public static String defaultString(String str, String defaultStr) {
        return str == null ? defaultStr : str;
    }

说明
Demo

 		System.out.println("1: " + StringUtils.defaultString(null, "a"));
        System.out.println("2: " + StringUtils.defaultString("", "a"));
        System.out.println("3: " + StringUtils.defaultString(" ", "a"));
        System.out.println("4: " + StringUtils.defaultString("\n\t", "a"));
        System.out.println("5: " + StringUtils.defaultString("aa", "a"));
        System.out.println("6: " + StringUtils.defaultString(" aaa", "a"));

1.12 capitalize

源码

public static String capitalize(String str) {
        int strLen = length(str);
        if (strLen == 0) {
            return str;
        } else {
            int firstCodepoint = str.codePointAt(0);
            int newCodePoint = Character.toTitleCase(firstCodepoint);
            if (firstCodepoint == newCodePoint) {
                return str;
            } else {
                int[] newCodePoints = new int[strLen];
                int outOffset = 0;
                int outOffset = outOffset + 1;
                newCodePoints[outOffset] = newCodePoint;

                int codepoint;
                for(int inOffset = Character.charCount(firstCodepoint); inOffset < strLen; inOffset += Character.charCount(codepoint)) {
                    codepoint = str.codePointAt(inOffset);
                    newCodePoints[outOffset++] = codepoint;
                }

                return new String(newCodePoints, 0, outOffset);
            }
        }
    }

说明

首字母大写

Demo

System.out.println(StringUtils.capitalize("abc"));

1.13 remove

源码

 public static String remove(String str, char remove) {
        if (!isEmpty(str) && str.indexOf(remove) != -1) {
            char[] chars = str.toCharArray();
            int pos = 0;

            for(int i = 0; i < chars.length; ++i) {
                if (chars[i] != remove) {
                    chars[pos++] = chars[i];
                }
            }

            return new String(chars, 0, pos);
        } else {
            return str;
        }
    }

    public static String remove(String str, String remove) {
        return !isEmpty(str) && !isEmpty(remove) ? replace(str, remove, "", -1) : str;
    }

说明

从str中去除removeStr

Demo

System.out.println(StringUtils.remove("abcd", "ab"));

1.14 countMatches

源码·

 public static int countMatches(CharSequence str, char ch) {
        if (isEmpty(str)) {
            return 0;
        } else {
            int count = 0;

            for(int i = 0; i < str.length(); ++i) {
                if (ch == str.charAt(i)) {
                    ++count;
                }
            }

            return count;
        }
    }

    public static int countMatches(CharSequence str, CharSequence sub) {
        if (!isEmpty(str) && !isEmpty(sub)) {
            int count = 0;

            for(int idx = 0; (idx = CharSequenceUtils.indexOf(str, sub, idx)) != -1; idx += sub.length()) {
                ++count;
            }

            return count;
        } else {
            return 0;
        }
    }

说明

计算字符串在另一个字符串中出现的次数

Demo

 int num = StringUtils.countMatches("UPDATE tb_table SET xx=?,xyz=?, sss=? WHERE id=?", "?");
        System.out.println(num);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值