[Jakarta Commons] 使用StringUtil类

本文介绍了 Apache Commons Lang 库中的 StringUtils 类提供的多种实用字符串操作方法,包括检查空字符串、缩写字符串、查找嵌套字符串、验证字符串类型、计算字符串出现频率及比较不同字符串等。通过这些方法可以有效提高字符串处理效率。

原文地址:http://www.blogjava.net/zJun/archive/2006/07/27/60370.html

org.apache.commons.lang.StringUtils中提供许多有用的字符串操作方法,了解这些方法,我们可以避免许多不必要的重复工作。下面介绍其中比较有用的几个方法:


检查空字符串:

StringUtils.isBlank(String str);
StringUtils.isNotBlank(String str);
 

 

缩写字符串:

 

String test   = " This is a test of the abbreviation. "
System.out.println( StringUtils.abbreviate( test,  10  ) );

[Console输出]
This is 
 

 


查找嵌套字符串:

String htmlContent   =     "  <html>\n  "     +
                      "   <head>\n "   +
                      "     <title>Test Page</title>\n "   +
                      "   </head>\n "   +
                      "   <body>\n "   +
                      "     <p>This is a TEST!</p>\n "   +
                      "   </body>\n "   +
                      " </html> " ;

//  Extract the title from this XHTML content 
String title  =  StringUtils.substringBetween(htmlContent,  " <title> " ,  " </title> " );
System.out.println(  " Title:  "   +  title );

[Console输出]
Title: Test Page 
 

 

 

 


验证字符串:

 

String test1   =     "  ORANGE  "      ;

String test2  =   " ICE9 " ;

String test3  =   " ICE CREAM " ;

String test4  =   " 820B Judson Avenue " ;


boolean  t1val  =  StringUtils.isAlpha( test1 );  //  returns true

boolean  t2val  =  StringUtils.isAlphanumeric( test2 );  //  returns true

boolean  t3val  =  StringUtils.isAlphaSpace( test3 );  //  returns true

boolean  t4val  =  

    StringUtils.isAlphanumericSpace( test4 );  //  returns true
 

 

计算字符串出现频率:


 

 

File manuscriptFile   =     new   File(  "  manuscript.txt  "      );

Reader reader  =   new  FileReader( manuscriptFile );

StringWriter stringWriter  =   new  StringWriter( );

while ( reader.ready( ) )  { writer.write( reader.read( ) ); }

String manuscript  =  stringWriter.toString( );

//  Convert string to lowercase

manuscript  =  StringUtils.lowerCase(manuscript);

//  count the occurrences of "futility"

int  numFutility  =  StringUtils.countMatches( manuscript,  " futility "  );
 

 


比较不同字符串:

int   dist   =   StringUtils.getLevenshteinDistance(   "  Word  "  ,   "  World  "       );

String diff  =  StringUtils.difference(  " Word " ,  " World "  );

int  index  =  StringUtils.indexOfDifference(  " Word " ,  " World "  );

System.out.println(  " Edit Distance:  "   +  dist );

System.out.println(  " Difference:  "   +  diff );

System.out.println(  " Diff Index:  "   +  index );

[Console输出]
Edit Distance:  2

Difference: ld

Diff Index:  3 
 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值