[Jakarta Commons] 使用StringUtil类

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

检查空字符串:

StringUtils.isBlank(Stringstr);
StringUtils.isNotBlank(Stringstr);

缩写字符串:

Stringtest = " Thisisatestoftheabbreviation. "
System.out.println(StringUtils.abbreviate(test,
10 ));

[Console输出]
Thisis

查找嵌套字符串:
StringhtmlContent = " <html>/n " +
" <head>/n " +
" <title>TestPage</title>/n " +
" </head>/n " +
" <body>/n " +
" <p>ThisisaTEST!</p>/n " +
" </body>/n " +
" </html> " ;

// ExtractthetitlefromthisXHTMLcontent
Stringtitle = StringUtils.substringBetween(htmlContent, " <title> " , " </title> " );
System.out.println(
" Title: " + title);

[Console输出]
Title:TestPage

验证字符串:
Stringtest1 = " ORANGE " ;

Stringtest2
= " ICE9 " ;

Stringtest3
= " ICECREAM " ;

Stringtest4
= " 820BJudsonAvenue " ;


boolean t1val = StringUtils.isAlpha(test1); // returnstrue

boolean t2val = StringUtils.isAlphanumeric(test2); // returnstrue

boolean t3val = StringUtils.isAlphaSpace(test3); // returnstrue

boolean t4val =

StringUtils.isAlphanumericSpace(test4);
// returnstrue

计算字符串出现频率:

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

Readerreader
= new FileReader(manuscriptFile);

StringWriterstringWriter
= new StringWriter();

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

Stringmanuscript
= stringWriter.toString();

// Convertstringtolowercase

manuscript
= StringUtils.lowerCase(manuscript);

// counttheoccurrencesof"futility"

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

比较不同字符串:
int dist = StringUtils.getLevenshteinDistance( " Word " , " World " );

Stringdiff
= StringUtils.difference( " Word " , " World " );

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

System.out.println(
" EditDistance: " + dist);

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

System.out.println(
" DiffIndex: " + index);

[Console输出]
EditDistance:
2

Difference:ld

DiffIndex:
3

转自-http://www.blogjava.net/zJun/archive/2006/07/27/60370.html

你可能感兴趣的:(commons)