`
biqing0427
  • 浏览: 55726 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

lang.StringUtils

    博客分类:
  • Unit
阅读更多

org.apache.commons.lang.StringUtils是操纵String类的实用类.  

 

http://dev2dev.bea.com.cn/techdoc/2005071902.html

处理字符串
  无论应用程序是基于Swing、J2EE或J2ME的,它都必须使用字符串。所以,尽管在Java中使用字符串相当简单,但是如果希望按照一定的条件 修改和处理字符串,事情就不那么简单了。您不得不在各种与字符串相关的类中寻找各种不常用的方法,然后想办法使其协同工作,以获得所需的结果。虽然有些 Lang方法与J2SE中的某些方法重叠,但在大多数情况下,一个Lang方法就可提供各种类中的多个J2SE方法的功能,从而帮助您获得所需的输出。
  Lang组件有许多专门用于字符串操作的类。现在我们将使用一个简单的Java应用程序来演示一些较为有用的类和方法。
  当应用程序接受用户输入时,由于用户可能会存在输入错误的情况,或用户可能以各种格式输入数据,而您希望只采用一种格式进行处理和存储,则通常会涉及到对字符串进行操作。
  例如,您有一个带输入框的窗体,用户在此输入框内输入许可证密钥。您希望允许输入1111-JAVA格式的密钥。您必须进行以下操作:

1. 检查是否为空字符串。
2. 忽略空格。
3. 密钥区分大小写。
4. 用“-”标记分隔密钥字符串,然后检查第一部分是否全部是数字,第二部分包含的字符是否只来自有效字符集“J”、“A”、“V”、“A”。
5. 两个部分均应有四个字符。
6. 第一部分的第四个数字应该是“0”。

  只有当密钥满足所有这些条件时,应用程序才会查询数据库,检查该密钥是否合法。
  如果不花大量的时间浏览String、StringTokenizer和其他类的API文档,您能完成以上的任务么?我不能,所以现在我将试着用Lang组件来管理验证。
清单1. checkLicenseKey()方法


/**
* Check if the key is valid
* @param key license key value
* @return true if key is valid, false otherwise.
*/
public static boolean checkLicenseKey(String key){
//checks if empty or null
if(StringUtils.isBlank(key)){
return false;
}

//delete all white space
key= StringUtils.deleteWhitespace(key);

//Split String using the - separator
String[] keySplit = StringUtils.split(key, "-");

//check lengths of whole and parts
if(keySplit.length != 2
|| keySplit[0].length() != 4
|| keySplit[1].length() != 4) {
return false;
}

//Check if first part is numeric
if(!StringUtils.isNumeric(keySplit[0])){
return false;
}

//Check if second part contains only
//the four characters 'J', 'A', 'V' and 'A'
if(! StringUtils.containsOnly(keySplit[1]
,new char[]{'J', 'A', 'V', 'A'})){
return false;
}

//Check if the fourth character
//in the first part is a '0'
if(StringUtils.indexOf(keySplit[0], '0') != 3){
return false;
}

//If all conditions are fulfilled, key is valid.
return true;
}
 

  在清单1中,我们使用了org.apache.commons.lang.StringUtils类中提供的各种方法,根据我们先前定义的所有 规则对字符串进行验证。isBlank()方法检查字符串是否为空。deleteWhitespace()方法确保字符串不包含空格。然后我们使用 split ()方法对字符串进行分隔,并使用isNumeric()、containsOnly()和indexOf()方法对密钥的两部分进行验证。
  请注意,尽管在J2SE中已经有了indexOf()方法,最好使用StringUtils中的indexOf()。与J2SE indexOf()方法不同,使用StringUtils indexOf()时无需担心空指针的问题。触发NullPointerException被认为是Java程序员最常犯的错误。Lang可以确保您不会 犯同样的错误。即使向indexOf()或其他此类方法传递一个null,都不会引发NullPointerException。indexOf()将直 接返回-1。
  这样,只需几行简单代码,就可以实现相应的功能,而采用其他方法需要编写很多行代码,而且十分麻烦。如果使用清单2中所示的主方法执行checkLicenseKey()方法,所得到的结果如清单3所示。

清单2. main()方法

public static void main(String[] args) {
String []key= {"1210-JVAJ","1211-JVAJ", "210-JVAJ", "1210-ZVAJ"};
for (int i=0; i > Is Valid");
}
else{
System.out.println(key[i]+ " >> Is InValid");
}
}
}
 

 

清单3. 输出

1210-JVAJ >> Is Valid
1211-JVAJ >> Is InValid
210-JVAJ >> Is InValid
1210-ZVAJ >> Is InValid

  大部分用于进行字符串操作的方法都隶属于org.apache.commons.lang.StringUtils,但也有其他的类可以使用。 CharUtils和CharSetUtils分别提供使用字符和字符集的实用方法。WordUtils是在2.0版中首次出现的类,用于承载专门用于处 理字的实用方法。不过,由于字符串和字的处理上有大量的重叠操作,使得此类似乎有点没有存在的必要了。RandomStringUtils类可以根据各种 规则生成随机字符串。
  现在,让我们了解一下Lang的另一个有用的方面:处理日期和时间的能力。

时间技术
  在Java中处理日期和时间是一件相当棘手的事。如果要使用java.text.SimpleDateFormat、 java.util.Calendar、java.util.Date等类,需要一定时间来适应,还需要对每一个涉及到的类和接口非常了解,才能顺利地处 理日期和时间。
  Lang组件彻底地简化了日期的处理,并可对其进行格式化。您可以轻松地格式化日期以进行显示、比较日期、舍入或截断日期,甚至能获取特定范围内的所有日期。

清单4. 处理日期和时间


public static void main(String[] args)
throws InterruptedException, ParseException {
//date1 created
Date date1= new Date();
//Print the date and time at this instant
System.out.println("The time right now is >>"+date1);

//Thread sleep for 1000 ms
Thread.currentThread().sleep(DateUtils.MILLIS_IN_SECOND);

//date2 created.
Date date2= new Date();

//Check if date1 and date2 have the same day
System.out.println("Is Same Day >> "
+ DateUtils.isSameDay(date1, date2));

//Check if date1 and date2 have the same instance
System.out.println("Is Same Instant >> "
+DateUtils.isSameInstant(date1, date2));

//Round the hour
System.out.println("Date after rounding >>"
+DateUtils.round(date1, Calendar.HOUR));

//Truncate the hour
System.out.println("Date after truncation >>"
+DateUtils.truncate(date1, Calendar.HOUR));

//Three dates in three different formats
String [] dates={"2005.03.24 11:03:26", "2005-03-24 11:03",
"2005/03/24"};

//Iterate over dates and parse strings to java.util.Date objects
for(int i=0; i >"+parsedDate);
}

//Display date in HH:mm:ss format
System.out.println("Now >>"
+DateFormatUtils.ISO_TIME_NO_T_FORMAT.format
(System.currentTimeMillis()));
}
 

  清单4演示了org.apache.commons.lang.DateUtils和 org.apache.commons.lang.DateFormatStringUtils类的部分功能。还有其他许多方法可以进行同样的操作,但输 入格式不同。故而,如果万一您必须分析和格式化一个日期值,只需要借助提供的方法之一,利用一行代码就可以实现了。
  执行清单4中代码后的输入如清单5所示。

清单5. 输出

The time right now is >>Sat Apr 09 14:40:41 GMT+05:30 2005
Is Same Day >> true
Is Same Instant >> false
Date after rounding >>Sat Apr 09 15:00:00 GMT+05:30 2005
Date after truncation >>Sat Apr 09 14:00:00 GMT+05:30 2005
Parsed Date is >>Thu Mar 24 11:03:26 GMT+05:30 2005
Parsed Date is >>Thu Mar 24 11:03:00 GMT+05:30 2005
Parsed Date is >>Thu Mar 24 00:00:00 GMT+05:30 2005
Now >>14:40:43

  在清单4中,我们创建了两个日期,这两个日期仅有一秒的差别。然后使用isSameInstant()和isSameDay()方法检查这两个日期是否相同。接下来将日期进行舍入和截断,然后使用在数组中指定的各种格式对特殊日期用例进行解析。
  将您的应用程序集成到第三方应用程序时,经常不能完全确定输入的格式。我曾经做过一个对旧版应用程序的集成,对于每个问题,该应用程序似乎总是有三个 答案。所以,如果必须对此类应用程序提供的日期进行解析,您需要提供三个和四个不同的日期格式。清单4中使用parseDate()方法就是为了完成这项 任务。这样,即使输入有变化,仍然能更对日期进行解析。还要注意,数组内模式的顺序与输入的顺序并不相同,但该方法仍然找到了适当的模式,并据此进行解 析。
  最后,我们按照ISO_TIME_NO_T_FORMAT格式(HH:mm:ss)对日期进行格式化并打印输入。现在我们将了解使用Lang生成常用方法toString()。

生成toString()方法
  经常要用到equals()、toString()和hashCode()方法。不过,谈到实际编写这些方法的实现时,不仅我们大多数人不愿意这样 做,而且我们也不能确定如何准确简单地编写这些方法。生成器程序包提供了一些实用类,可以帮助您方便地创建这些方法的实现。大多数情况下,只需要一行代码 即可。下面我们将了解Lang的toString功能。

toString()方法
  您可能没有注意到,在清单4中,即使我们向System.out.println()传递一个java.util.Date对象,所获得的输出仍然是 正确的日期和时间显示。传递对象引用时,将自动调用toString()方法,所以可以实现这一点。那么,在我们的示例中实际上调用了 java.util.Date类的toString()方法,我们能够得到正确的输出是因为有人重写了java.util.Date类中的 java.lang.Object类的toString()方法。
  如果没有重写toString()方法,则获得的输出只是类名称和hashcode的名称。将不会显示类中的任何数据。所以,如果编写了一个新类,且希望能得到正确的打印输出,则需要重写该类中的toString()方法。

清单6. toString()方法


public class Computer {

String processor;
String color;
int cost;

/** Creates a new instance of Computer */
public Computer(String processor, String color, int cost) {
this.processor=processor;
this.color=color;
this.cost=cost;
}

public static void main(String[] args) {
Computer myComp=new Computer("Pentium","black",1000);
System.out.println(myComp);
}
public String toString(){
return ToStringBuilder.reflectionToString(this);
/*
return ToStringBuilder.reflectionToString(this
, ToStringStyle.SHORT_PREFIX_STYLE);
return ToStringBuilder.reflectionToString(this
, ToStringStyle.MULTI_LINE_STYLE);
return new ToStringBuilder(this)
.append("processor", processor).toString();
*/
}
}
 

  清单6演示了具有三个字段的Computer类。其中值得关注的是toString()方法。调用reflectionToString()方 法可以判断哪些是类中的字段,然后打印其名称和值。main()方法中,我们只创建了该类的一个实例,然后将其打印出来。该类的输出为 dev2dev.Computer@f6a746[processor=Pentium,color=black,cost=1000]。
  因而,如果不希望花太多精力,但又需要您的类有toString()实现,最简单的方法莫过于将这两行代码复制并粘贴到您的所有类中。如果希望更好地 控制生成的结果,请参见注释中提到的选项。通过创建ToStringBuilder的新实例,可以对输出应用各种样式,甚至生成全部输出。如果按照列出的 顺序执行了全部四个返回语句,则输出如清单7所示。

清单7. 基于ToStringBuilder方法的四个可能输出

1) dev2dev.Computer@f6a746[processor=Pentium,color=black,cost=1000]
2) Computer[processor=Pentium,color=black,cost=1000]
3) dev2dev.Computer@f6a746[
processor=Pentium
color=black
cost=1000
]
4) dev2dev.Computer@192d342[processor=Pentium]

对象比较与排序
  经常需要对数据对象进行比较,并据此进行排序。那么我们如何对清单6中所给出的Computer类的对象进行比较和排序呢?
  您猜猜!让我们使用Lang根据计算机的成本对Computer对象进行排序。若要比较对象,需要实现java.lang.Comparable接 口。此接口具有惟一的方法compareTo(Object)。此方法实现将当前对象和传递给此方法的对象进行比较。如果此对象小于、等于或大于指定的对 象,此方法将分别返回负数、零或正数。
  为了对Computer对象进行比较,在Computer类中实现compareTo() 方法,如清单8所示。

清单8. compareTo()方法

public int compareTo(Object obj) {
Computer anotherComputer = (Computer)obj;
//return new CompareToBuilder().reflectionCompare
(this, anotherComputer);
return new CompareToBuilder().
append(this.cost, anotherComputer.cost).toComparison();
}
 

 

  然后,为了实际进行比较,我们编写一个名为ComputerSor的简单类,如清单9中所示。我们只向ArrayList添加三个对象,然后进行排序。

清单9. ComputerSort类


public class ComputerSort {

public static void main(String[] args) {
ArrayList computerList = new ArrayList();
computerList.add(new Computer("Pentium","black", 1000));
computerList.add(new Computer("Pentium","chocolate", 334));
computerList.add(new Computer("Pentium","darkgray", 2234));

Collections.sort(computerList);
System.out.println(computerList);
}

}
 

  执行ComputerSort时,将看到对象根据cost字段的值进行了排序。CompareToBuilder与 ToStringBuilder类似,也有一个基于反射的用法选项。我们已对清单8中的compareTo()方法中的位元进行了注释,因为,在此种情况 下,反射选项将比较所有字段,最终获得不正确的结果。如果既不希望比较当前类中的字段,也不希望比较其超类中的字段,CompareToBuilder也 提供了可以用于此用途的方法。执行 ComputerSort类的输出如清单10中所示。

清单10. 排序后的Computer对象

[dev2dev.Computer@cf2c80[processor=Pentium,color=chocolate,cost=334]
, dev2dev.Computer@12dacd1[processor=Pentium,color=black,cost=1000]
, dev2dev.Computer@1ad086a[processor=Pentium,color=darkgray,cost=2234]]

 

分享到:
评论
1 楼 biqing0427 2008-02-15  
http://ttitfly.iteye.com/blog/92701

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

查找嵌套字符串:
java 代码

1. String htmlContent = " n " +
2. " n " +
3. " n " +
4. " n " +
5. " n " +
6. "

This is a TEST!
n " +
7. " n " +
8. " " ;
9.
10. // Extract the title from this XHTML content
11. String title = StringUtils.substringBetween(htmlContent, " " );
12. System.out.println( " Title: " + title );
13.
14. [Console输出]
15. 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

相关推荐

    org.apache.commons.lang3.StringUtils.jar

    StringUtils.isEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) { //多次反向代理后会有多个ip值,第一个ip才是真实ip int index = ip.indexOf(","); if (index != -1) { return ip....

    org.apache.commons.lang3.StringUtils.jar.rar

    org.apache.commons.lang3.StringUtils.jar,打开是common-lang3.jar文件,以及使用方法,根据使用方法使用即可,绝对可靠

    org.apache.commons.lang jar包下载(commons-lang3-3.1.jar)

    org.apache.commons.lang.StringUtils.class org.apache.commons.lang.SystemUtils.class org.apache.commons.lang.UnhandledException.class org.apache.commons.lang.Validate.class org.apache.commons.lang....

    org.apache.commons.lang jar包下载

    org.apache.commons.lang.StringUtils.class org.apache.commons.lang.SystemUtils.class org.apache.commons.lang.UnhandledException.class org.apache.commons.lang.Validate.class org.apache.commons.lang....

    commons-lang3-3.1jar:org.apache.commons.lang3.StringUtils等.

    包含有org.apache.commons.lang3.StringUtils; org.apache.commons.lang3.reflect.FieldUtils等类

    commons-lang3-3.1 StringUtils字符串jar包

    commons-lang3-3.1 StringUtils字符串jar包 org.apache.commons.lang3.StringUtils的jar包

    commons-lang.jar

    org.apache.commons.lang.StringUtils.class org.apache.commons.lang.SystemUtils.class org.apache.commons.lang.UnhandledException.class org.apache.commons.lang.Validate.class org.apache.commons.lang....

    org.apache.commons.lang jar下载

    org.apache.commons.lang所有包的集合,

    自定封装StringUtils常用方法

    继承了org.apache.commons.lang3.StringUtils工具类,加入了部分常用方法,使用时直接添加到项目的公共utils下,同时在pom.xml加入依赖: <!-- ...

    org.apache.commons.lang包

    Apache Commons Lang资源包,下载解压缩后,可获得api文档,源码,jar包,用于开发

    Java字符串加密使用的一个jar包 commons-lang3-3.1.jar下载

    org.apache.commons.lang3.StringUtils org.apache.commons.lang3.ArrayUtils.class org.apache.commons.lang3.BitField.class org.apache.commons.lang3.CharUtils.class org.apache.commons.lang3.ClassUtils....

    commons-lang-StringUtils.zip

    jar包中的StringUtils类用于操作字符串的各种判断和截取

    StringUtils (Lang 2_3 API)

    StringUtils (Lang 2_3 API)

    DX2 ndsns19楼蓝色风格

    DX2 ndsns19楼蓝色风格DX2 ndsns19楼蓝色风格DX2 ndsns19楼蓝色风格DX2 ndsns19楼蓝色风格DX2 ndsns19楼蓝色风格DX2 ndsns19楼蓝色风格DX2 ndsns19楼蓝色风格DX2 ndsns19楼蓝色风格DX2 ndsns19楼蓝色风格DX2 ndsns19...

    定时任务cron 解析为中文.docx

    5 import org.apache.commons.lang.StringUtils; 6 import org.assertj.core.util.Lists; 7 import org.quartz.CronExpression; 8 import org.springframework.util.Assert; 9 10 import java.text.Parse...

    org.apache.poi JAR包

    import org.apache.commons.lang.StringUtils; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFFont; import org...

    org.apache.poi jar包

    import org.apache.commons.lang.StringUtils; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFFont; import org...

    commons-lang3-3.11-sources.jar

    import org.apache.commons.lang.StringUtils;的时候出错解决方法 菜鸟一枚,才开始学习后台以及idea,导入项目就遇到错误,这边的解决方法也是为自己备注一下以免下次遇到忘记了。 错误如下: 这里写图片描述 ...

    StringUtils

    StringUtils 方法的操作对象是 java.lang.String 类型的对象,是 ...除了构造器,StringUtils 中一共有130多个方法,并且都是 static 的,所以我们可以这样调用 StringUtils.xxx() 下面分别对一些常用方法做简要介绍:

    StringUtils 中文API

    org.apache.commons.lang.StringUtils 类的中文API doc文档版本

Global site tag (gtag.js) - Google Analytics