---
title: "Jakarta Commons cookbook读书笔记--Commons Lang(2)"
author: "Heis"
date: "2009-11-18T16:29:31Z"
tags: []
slug: "jakarta-commons-cookbook-commons-lang-2"
draft: false
lastmod: "2009-11-18T16:37:28Z"
id: 519733
url: "https://heis.iteye.com/blog/519733"
---

**[《Jakarta Commons cookbook读书笔记》系列文章](/category/86283)**

 

**1.10 对null安全的（null-safe）字符串操作org.apache.commons.lang.StringUtils**

解释几个该包内约定术语  
\# 空字符串(empty) - 长度为零的字符串 ("")  
\# 空格(space) - 空格字符(' ', char 32)  
\# 空白(whitespace) - 符合Character.isWhitespace(char)的字符  
\# 修剪字符(trim) - ASCII码表中取值小于32的字符,等同String.trim()清除的字符

**1.10.1 判断空字符串，空格及null**  
       isEmpty()判断是否为空字符串或null  
       isNotEmpty()==!isEmpty()  
       isBlank()判断是否为空格，空字符串或null  
       isNotBlank()==!isBlank()

**1.10.2 修剪字符串**  
       trim()加入null判断的String.trim()  
       strip()修剪string前后的空白，或指定字符串  
        
**1.10.3 缩减字符串**  
       abbreviate()可以按照目标长度缩减字符串，若小于目标长度，最后三位字符以"..."代替

```
StringUtils.abbreviate("How to abbreviate a string?",9) -> How to...
```

 

**1.10.4 清除回车符(\\r)和换行符(\\n)**

       chomp()  
        
**1.10.5 反转字符串和反转句子的单词顺序**

       reverse()

```
       StringUtils.reverse("I'm heis") ->sieh m'I
       StringUtils.reverseSentence("I'm heis") ->heis I'm
```

 

**1.10.6 检测字符串内容**  
       isNumeric()判断是否只包含0-9  
       isAlpha()判断是否只包含字母  
       isAlphanumeric()判断是否只包含字母和数字的组合  
       isAlphaSpace()判断是否只包含空格和字母

**1.10.7 检测字符串出现频率**  
       countMatches()

**1.10.8 substring变种形式**

```
StringUtils.substringBetween("[hello,heis]","[","]") ->hello,heis
```

 

       substringBefore()捕获指定字符串之前的内容  
       substringAfter()捕获指定字符串之后的内容  
       substringBeforeLast()捕获指定字符串最后出现处之前的内容  
       substringAfterLast()捕获指定字符串最后出现处之后的内容

**1.10.9 计算字符串的差别**  
       difference(str1，str2)输出第二个字符串与第一个相差的字符串

```
StringUtils.difference("word","world") ->ld
```

 

        
       indexOfDifference(str1,str2)输出两个字符串相差的下标

```
StringUtils.indexOfDifference("word","world") ->3
```

 

        
       getLevenshteinDistance(str1,str2)输出两个字符编辑距离，即一个字符串要转换到另一个字符串需要插入，删除和替换的字符的次数。

```
StringUtils.getLevenshteinDistance("steve","stereo") ->2
StringUtils.getLevenshteinDistance("heis","hello") ->3
```

 

        
**1.10.10 StringUtils提供了null-safe的indexOf(),subString()，replace()等，这些方法功能与java.lang.String内方法一致** 。

 

[**《Jakarta Commons cookbook读书笔记》系列文章**](/category/86283)