commons学习(二)StringUtils

取得commons-lang-2.1.jar后加入自己工程的lib目录就可以了.如果用户不允许使用commons,那末打开其源码把具体函数加入自己的代码也可以,当然需要尊重人家的知识产权。

以下代码经过测试,测试环境(WinXp+Eclipse3.1+JDK1.5+commons-lang-2.1),我在有些地方修改了一下。


Jakarta Commons Cookbook—01—Manipulating Text
Commons之字符串操作
要利用Jakarta Commons来进行字符串操作,首先需要加载需要用到的包:
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.WordUtils;

以下是StringUtils的各项用法
1.空字符串检查
使用函数: StringUtils.isBlank(testString)
函数介绍: 当testString为空,长度为零或者仅由空白字符(whitespace)组成时,返回True;否则返回False
例程:
    String test = "";
String test2 = "\n\n\t";
String test3 = null;
String test4 = "Test";

System.out.println( "test blank? " + StringUtils.isBlank( test ) );
System.out.println( "test2 blank? " + StringUtils.isBlank( test2 ) );
System.out.println( "test3 blank? " + StringUtils.isBlank( test3 ) );
System.out.println( "test4 blank? " + StringUtils.isBlank( test4 ) );
输出如下:
test blank? true
test2 blank? true
test3 blank? true
test4 blank? False
函数StringUtils.isNotBlank(testString)的功能与StringUtils.isBlank(testString)相反.


2.清除空白字符
使用函数: StringUtils.trimToNull(testString)
函数介绍:清除掉testString首尾的空白字符,如果仅testString全由空白字符
(whitespace)组成则返回null
例程:
  String test1 = "\t";
String test2 = " A Test ";
String test3 = null;

System.out.println( "test1 trimToNull: " + StringUtils.trimToNull( test1 ) );
System.out.println( "test2 trimToNull: " + StringUtils.trimToNull( test2 ) );
System.out.println( "test3 trimToNull: " + StringUtils.trimToNull( test3 ) );


输出如下:
test1 trimToNull: null
test2 trimToNull: A Test
test3 trimToNull: null

注意:函数StringUtils.trim(testString)与
StringUtils.trimToNull(testString)功能类似,但testString由空白字符
(whitespace)组成时返回零长度字符串。


3.取得字符串的缩写
使用函数: StringUtils.abbreviate(testString,width)和StringUtils.abbreviate(testString,offset,width)
函数介绍:在给定的width内取得testString的缩写,当testString的长度小于width则返回原字符串.
例程:
    String test = "This is a test of the abbreviation.";
String test2 = "Test";

System.out.println( StringUtils.abbreviate( test, 15 ) );
System.out.println( StringUtils.abbreviate( test, 5,15 ) );
System.out.println( StringUtils.abbreviate( test2, 10 ) );
输出如下:
This is a te...
...is a test...
Test

4.劈分字符串
使用函数: StringUtils.split(testString,splitChars,arrayLength)
函数介绍:splitChars中可以包含一系列的字符串来劈分testString,并可以设定得
到数组的长度.注意设定长度arrayLength和劈分字符串间有抵触关系,建议一般情况下
不要设定长度.
例程:
    String input = "A b,c.d|e";
String input2 = "Pharmacy, basketball funky";


String[] array1 = StringUtils.split( input, " ,.|");
String[] array2 = StringUtils.split( input2, " ,", 2 );


System.out.println( ArrayUtils.toString( array1 ) );
System.out.println( ArrayUtils.toString( array2 ) );

输出如下:
{A,b,c,d,e}
{Pharmacy,basketball funky}

5.查找嵌套字符串
使用函数:StringUtils.substringBetween(testString,header,tail)
函数介绍:在testString中取得header和tail之间的字符串。不存在则返回空
例程:
    String htmlContent = "ABC1234ABC4567";
System.out.println(StringUtils.substringBetween(htmlContent, "1234", "4567"));
System.out.println(StringUtils.substringBetween(htmlContent, "12345", "4567"));
输出如下:
ABC
null


6.去除尾部换行符
使用函数:StringUtils.chomp(testString)
函数介绍:去除testString尾部的换行符
例程:
    String input = "Hello\n";
System.out.println( StringUtils.chomp( input ));
String input2 = "Another test\r\n";
System.out.println( StringUtils.chomp( input2 ));
输出如下:
Hello
Another test


7.重复字符串
使用函数:StringUtils.repeat(repeatString,count)
函数介绍:得到将repeatString重复count次后的字符串
例程:
System.out.println( StringUtils.repeat( "*", 10));
System.out.println( StringUtils.repeat( "China ", 5));
输出如下:
**********
China China China China China

其他函数:StringUtils.center( testString, count,repeatString );
函数介绍:把testString插入将repeatString重复多次后的字符串中间,得到字符串
的总长为count
例程:
System.out.println( StringUtils.center( "China", 11,"*"));
输出如下:
***China***


8.颠倒字符串
使用函数:StringUtils.reverse(testString)
函数介绍:得到testString中字符颠倒后的字符串
例程:
System.out.println( StringUtils.reverse("ABCDE"));
输出如下:
EDCBA

9.判断字符串内容的类型
函数介绍:
StringUtils.isNumeric( testString ) :如果testString全由数字组成返回True
StringUtils.isAlpha( testString ) :如果testString全由字母组成返回True
StringUtils.isAlphanumeric( testString ) :如果testString全由数字或数字组
成返回True
StringUtils.isAlphaspace( testString ) :如果testString全由字母或空格组
成返回True

例程:
String state = "Virginia";
System.out.println( "Is state number? " + StringUtils.isNumeric(
state ) );
System.out.println( "Is state alpha? " + StringUtils.isAlpha( state )
);
System.out.println( "Is state alphanumeric? " +StringUtils.isAlphanumeric( state ) );
System.out.println( "Is state alphaspace? " + StringUtils.isAlphaSpace( state ) );
输出如下:
Is state number? false
Is state alpha? true
Is state alphanumeric? true
Is state alphaspace? true

10.取得某字符串在另一字符串中出现的次数
使用函数:StringUtils.countMatches(testString,seqString)
函数介绍:取得seqString在testString中出现的次数,未发现则返回零
例程:
System.out.println(StringUtils.countMatches( "Chinese People", "e"
));
输出:
4

11.部分截取字符串
使用函数:
StringUtils.substringBetween(testString,fromString,toString ):取得两字符
之间的字符串
StringUtils.substringAfter( ):取得指定字符串后的字符串
StringUtils.substringBefore( ):取得指定字符串之前的字符串
StringUtils.substringBeforeLast( ):取得最后一个指定字符串之前的字符串
StringUtils.substringAfterLast( ):取得最后一个指定字符串之后的字符串

函数介绍:上面应该都讲明白了吧。
例程:
String formatted = " 25 * (30,40) [50,60] | 30";
System.out.print("N0: " + StringUtils.substringBeforeLast( formatted, "*" ) );
System.out.print(", N1: " + StringUtils.substringBetween( formatted, "(", "," ) );
System.out.print(", N2: " + StringUtils.substringBetween( formatted, ",", ")" ) );
System.out.print(", N3: " + StringUtils.substringBetween( formatted, "[", "," ) );
System.out.print(", N4: " + StringUtils.substringBetween( formatted, ",", "]" ) );
System.out.print(", N5: " + StringUtils.substringAfterLast( formatted, "|" ) );

输出如下:
N0: 25 , N1: 30, N2: 40, N3: 50, N4: 40) [50,60, N5: 30

看commons包时的相关练习,可以用这个包提高编码效率。

package org.raistlin.test.apache;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.CharSet;
import org.apache.commons.lang.CharSetUtils;
import org.apache.commons.lang.ClassUtils;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.SerializationUtils;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.SystemUtils;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang.time.DateUtils;
import org.apache.commons.lang.time.StopWatch;

public class LangDemo
{
public void charSetDemo()
{
System.out.println("**CharSetDemo**");
CharSet charSet = CharSet.getInstance("aeiou");
String demoStr = "The quick brown fox jumps over the lazy dog.";
int count = 0;
for (int i = 0, len = demoStr.length(); i < len; i++)
{
if (charSet.contains(demoStr.charAt(i)))
{
count++;
}
}
System.out.println("count: " + count);
}

public void charSetUtilsDemo()
{
System.out.println("**CharSetUtilsDemo**");
System.out.println("计算字符串中包含某字符数.");
System.out.println(CharSetUtils.count(
"The quick brown fox jumps over the lazy dog.", "aeiou"));

System.out.println("删除字符串中某字符.");
System.out.println(CharSetUtils.delete(
"The quick brown fox jumps over the lazy dog.", "aeiou"));

System.out.println("保留字符串中某字符.");
System.out.println(CharSetUtils.keep(
"The quick brown fox jumps over the lazy dog.", "aeiou"));

System.out.println("合并重复的字符.");
System.out.println(CharSetUtils.squeeze("a bbbbbb c dd", "b d"));
}

public void objectUtilsDemo()
{
System.out.println("**ObjectUtilsDemo**");
System.out.println("Object为null时,默认打印某字符.");
Object obj = null;
System.out.println(ObjectUtils.defaultIfNull(obj, "空"));

System.out.println("验证两个引用是否指向的Object是否相等,取决于Object的equals()方法.");
Object a = new Object();
Object b = a;
Object c = new Object();
System.out.println(ObjectUtils.equals(a, b));
System.out.println(ObjectUtils.equals(a, c));

System.out.println("用父类Object的toString()方法返回对象信息.");
Date date = new Date();
System.out.println(ObjectUtils.identityToString(date));
System.out.println(date);

System.out.println("返回类本身的toString()方法结果,对象为null时,返回0长度字符串.");
System.out.println(ObjectUtils.toString(date));
System.out.println(ObjectUtils.toString(null));
System.out.println(date);
}

public void serializationUtilsDemo()
{
System.out.println("*SerializationUtils**");
Date date = new Date();
byte[] bytes = SerializationUtils.serialize(date);
System.out.println(ArrayUtils.toString(bytes));
System.out.println(date);

Date reDate = (Date) SerializationUtils.deserialize(bytes);
System.out.println(reDate);
System.out.println(ObjectUtils.equals(date, reDate));
System.out.println(date == reDate);

FileOutputStream fos = null;
FileInputStream fis = null;
try
{
fos = new FileOutputStream(new File("d:/test.txt"));
fis = new FileInputStream(new File("d:/test.txt"));
SerializationUtils.serialize(date, fos);
Date reDate2 = (Date) SerializationUtils.deserialize(fis);

System.out.println(date.equals(reDate2));

}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
finally
{
try
{
fos.close();
fis.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}

}

public void randomStringUtilsDemo()
{
System.out.println("**RandomStringUtilsDemo**");
System.out.println("生成指定长度的随机字符串,好像没什么用.");
System.out.println(RandomStringUtils.random(500));

System.out.println("在指定字符串中生成长度为n的随机字符串.");
System.out.println(RandomStringUtils.random(5, "abcdefghijk"));

System.out.println("指定从字符或数字中生成随机字符串.");
System.out.println(RandomStringUtils.random(5, true, false));
System.out.println(RandomStringUtils.random(5, false, true));

}

public void stringUtilsDemo()
{
System.out.println("**StringUtilsDemo**");
System.out.println("将字符串重复n次,将文字按某宽度居中,将字符串数组用某字符串连接.");
String[] header = new String[3];
header[0] = StringUtils.repeat("*", 50);
header[1] = StringUtils.center(" StringUtilsDemo ", 50, "^O^");
header[2] = header[0];
String head = StringUtils.join(header, "\n");
System.out.println(head);

System.out.println("缩短到某长度,用...结尾.");
System.out.println(StringUtils.abbreviate(
"The quick brown fox jumps over the lazy dog.", 10));
System.out.println(StringUtils.abbreviate(
"The quick brown fox jumps over the lazy dog.", 15, 10));

System.out.println("返回两字符串不同处索引号.");
System.out.println(StringUtils.indexOfDifference("aaabc", "aaacc"));

System.out.println("返回两字符串不同处开始至结束.");
System.out.println(StringUtils.difference("aaabcde", "aaaccde"));

System.out.println("截去字符串为以指定字符串结尾的部分.");
System.out.println(StringUtils.chomp("aaabcde", "de"));

System.out.println("检查一字符串是否为另一字符串的子集.");
System.out.println(StringUtils.containsOnly("aad", "aadd"));

System.out.println("检查一字符串是否不是另一字符串的子集.");
System.out.println(StringUtils.containsNone("defg", "aadd"));

System.out.println("检查一字符串是否包含另一字符串.");
System.out.println(StringUtils.contains("defg", "ef"));
System.out.println(StringUtils.containsOnly("ef", "defg"));

System.out.println("返回可以处理null的toString().");
System.out.println(StringUtils.defaultString("aaaa"));
System.out.println("?" + StringUtils.defaultString(null) + "!");

System.out.println("去除字符中的空格.");
System.out.println(StringUtils.deleteWhitespace("aa bb cc"));

System.out.println("判断是否是某类字符.");
System.out.println(StringUtils.isAlpha("ab"));
System.out.println(StringUtils.isAlphanumeric("12"));
System.out.println(StringUtils.isBlank(""));
System.out.println(StringUtils.isNumeric("123"));
}

public void systemUtilsDemo()
{
System.out.println(genHeader("SystemUtilsDemo"));
System.out.println("获得系统文件分隔符.");
System.out.println(SystemUtils.FILE_SEPARATOR);

System.out.println("获得源文件编码.");
System.out.println(SystemUtils.FILE_ENCODING);

System.out.println("获得ext目录.");
System.out.println(SystemUtils.JAVA_EXT_DIRS);

System.out.println("获得java版本.");
System.out.println(SystemUtils.JAVA_VM_VERSION);

System.out.println("获得java厂商.");
System.out.println(SystemUtils.JAVA_VENDOR);
}

public void classUtilsDemo()
{
System.out.println(genHeader("ClassUtilsDemo"));
System.out.println("获取类实现的所有接口.");
System.out.println(ClassUtils.getAllInterfaces(Date.class));

System.out.println("获取类所有父类.");
System.out.println(ClassUtils.getAllSuperclasses(Date.class));

System.out.println("获取简单类名.");
System.out.println(ClassUtils.getShortClassName(Date.class));

System.out.println("获取包名.");
System.out.println(ClassUtils.getPackageName(Date.class));

System.out.println("判断是否可以转型.");
System.out.println(ClassUtils.isAssignable(Date.class, Object.class));
System.out.println(ClassUtils.isAssignable(Object.class, Date.class));
}

public void stringEscapeUtilsDemo()
{
System.out.println(genHeader("StringEcsapeUtils"));
System.out.println("转换特殊字符.");
System.out.println("html:" + StringEscapeUtils.escapeHtml("

"));
System.out.println("html:"
+ StringEscapeUtils.unescapeHtml("<p>"));
}

private final class BuildDemo
{
String name;

int age;

public BuildDemo(String name, int age)
{
this.name = name;
this.age = age;
}

public String toString()
{
ToStringBuilder tsb = new ToStringBuilder(this,
ToStringStyle.MULTI_LINE_STYLE);
tsb.append("Name", name);
tsb.append("Age", age);
return tsb.toString();
}

public int hashCode()
{
HashCodeBuilder hcb = new HashCodeBuilder();
hcb.append(name);
hcb.append(age);
return hcb.hashCode();
}

public boolean equals(Object obj)
{
if (!(obj instanceof BuildDemo))
{
return false;
}
BuildDemo bd = (BuildDemo) obj;
EqualsBuilder eb = new EqualsBuilder();
eb.append(name, bd.name);
eb.append(age, bd.age);
return eb.isEquals();
}
}

public void builderDemo()
{
System.out.println(genHeader("BuilderDemo"));
BuildDemo obj1 = new BuildDemo("a", 1);
BuildDemo obj2 = new BuildDemo("b", 2);
BuildDemo obj3 = new BuildDemo("a", 1);

System.out.println("toString()");
System.out.println(obj1);
System.out.println(obj2);
System.out.println(obj3);

System.out.println("hashCode()");
System.out.println(obj1.hashCode());
System.out.println(obj2.hashCode());
System.out.println(obj3.hashCode());

System.out.println("equals()");
System.out.println(obj1.equals(obj2));
System.out.println(obj1.equals(obj3));
}

public void numberUtils()
{
System.out.println(genHeader("NumberUtils"));
System.out.println("字符串转为数字(不知道有什么用).");
System.out.println(NumberUtils.stringToInt("ba", 33));

System.out.println("从数组中选出最大值.");
System.out.println(NumberUtils.max(new int[] { 1, 2, 3, 4 }));

System.out.println("判断字符串是否全是整数.");
System.out.println(NumberUtils.isDigits("123.1"));

System.out.println("判断字符串是否是有效数字.");
System.out.println(NumberUtils.isNumber("0123.1"));
}

public void dateFormatUtilsDemo()
{
System.out.println(genHeader("DateFormatUtilsDemo"));
System.out.println("格式化日期输出.");
System.out.println(DateFormatUtils.format(System.currentTimeMillis(),
"yyyy-MM-dd HH:mm:ss"));

System.out.println("秒表.");
StopWatch sw = new StopWatch();
sw.start();

for (Iterator iterator = DateUtils.iterator(new Date(),
DateUtils.RANGE_WEEK_CENTER); iterator.hasNext();)
{
Calendar cal = (Calendar) iterator.next();
System.out.println(DateFormatUtils.format(cal.getTime(),
"yy-MM-dd HH:mm"));
}

sw.stop();
System.out.println("秒表计时:" + sw.getTime());

}

private String genHeader(String head)
{
String[] header = new String[3];
header[0] = StringUtils.repeat("*", 50);
header[1] = StringUtils.center(" " + head + " ", 50, "^O^");
header[2] = header[0];
return StringUtils.join(header, "\n");
}

/**
* @param args
*/
public static void main(String[] args)
{
LangDemo langDemo = new LangDemo();

langDemo.charSetDemo();
langDemo.charSetUtilsDemo();
langDemo.objectUtilsDemo();
langDemo.serializationUtilsDemo();
langDemo.randomStringUtilsDemo();
langDemo.stringUtilsDemo();
langDemo.systemUtilsDemo();
langDemo.classUtilsDemo();
langDemo.stringEscapeUtilsDemo();
langDemo.builderDemo();
langDemo.numberUtils();
langDemo.dateFormatUtilsDemo();

}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值