这儿有你的一套测试案例,证明上述:
public class Test {
public static void main(String[] args){
test("x,y");
test(",y");
test("");
test(",");
}
private static void test(String x){
System.out.println("testing split on value ["+x+"]");
String y = x.split(",")[0];
if(null == y){
System.out.println("x returned a null value for first array element");
} else if(y.length() < 1) {
System.out.println("x returned an empty string for first array element");
} else {
System.out.println("x returned a value for first array element");
}
}
}
运行时,这是你会得到什么:
$ javac Test.java && java Test
testing split on value [x,y]
x returned a value for first array element
testing split on value [,y]
x returned an empty string for first array element
testing split on value []
x returned an empty string for first array element
testing split on value [,]
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at Test.test(Test.java:11)
at Test.main(Test.java:6)
这很容易通过简单地写检查这种行为一个微小的程序,尝试这种情况下,看看你得到了什么 – mfrankli 2012-03-16 19:12:28
它是。即使它不包含给定的正则表达式,它总是会返回初始字符串。 – 2012-03-16 19:12:46
@mfrankli,谢谢。这几乎是有用的建议。很明显,我可以编写一个测试程序(并且有)...我正在询问一些我可能没有考虑或想到的异常情况。 – 2012-03-16 19:14:19