Apache Commons Lang使用-StringUtils

本文介绍了Apache Commons Lang中的StringUtils,讲解了其包括字符串比较、空判断、URL处理等常用方法,强调了这些方法的null安全性和简化代码的优势。

Apache Commons Lang使用

Commons Lang对应的包,并查看相应的文档

StringUtils

StringUtils位于org.apache.commons.lang包下

参考Apache Commons Lang StringUtils介绍一些常用的方法。

1.public static boolean equals(CharSequence str1, CharSequence str2)方法

文档介绍如下:

比较两个CharSequences,如果表示相同返回true
处理null会没有异常。两个null会被认为是相同的,比较是大小写敏感的。

 StringUtils.equals(null, null)   = true
 StringUtils.equals(null, "abc")  = false
 StringUtils.equals("abc", null)  = false
 StringUtils.equals("abc", "abc") = true
 StringUtils.equals("abc", "ABC") = false

为什么要使用这个方法呢?如下的代码:

public void doStuffWithString(String stringParam) {
    if(stringParam.equals("MyStringValue")) {
        // do stuff
    }
}

这里可能会抛出一个NullPointerException异常

一般的做法是:

public void safeDoStuffWithString1(String stringParam) {
    if(stringParam != null && stringParam.equals("MyStringValue")) {
        // do stuff
    }
}

public void safeDoStuffWithString2(String stringParm) {
    if("MyStringValue".equals(stringParam)) {
        // do stuff
    }
}

但使用StringUtils.equals,使用起来会简单,而且是null安全的。

2.isEmpty, isNotEmpty, isBlank, isNotBlank
通常的做法是,使用java.lang.String.isEmpty(),并检查是否是null

if(myString != null && !myString.isEmpty()) { // urghh
   // Do stuff with myString
}

使用StringUtils

if(StringUtils.isNotEmpty(myString)) { // much nicer
   // Do stuff with myString
}

Blank与Empty的区别

String someWhiteSpace = "    \t  \n";
StringUtils.isEmpty(someWhiteSpace); // false
StringUtils.isBlank(someWhiteSpace); // true

isEmpty检查的是否为""或者null

 StringUtils.isEmpty(null)      = true
 StringUtils.isEmpty("")        = true
 StringUtils.isEmpty(" ")       = false
 StringUtils.isEmpty("bob")     = false
 StringUtils.isEmpty("  bob  ") = false

isBlank检查的是否为whitespace, empty (“”) 或者 null

 StringUtils.isBlank(null)      = true
 StringUtils.isBlank("")        = true
 StringUtils.isBlank(" ")       = true
 StringUtils.isBlank("bob")     = false
 StringUtils.isBlank("  bob  ") = false

3.public static String[] split(String str, String separatorChars)方法

如下的例子:

public void possiblyNotWhatYouWant() {
    String contrivedExampleString = "one.two.three.four";
    String[] result = contrivedExampleString.split(".");
    System.out.println(result.length); // 0
}

result.length的结果为0,但只有加上一对斜杠,就可以得到正确的结果。

但是使用StringUtils的方法就不会出现这种情况。

4.public static String join(Iterable iterable, String separator)方法

String[] numbers = {"one", "two", "three"};
StringUtils.join(numbers,",");  // returns "one,two,three"
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值