今天在写Java程序时,发现了之前犯下的一个错误。
Java中提供了许多非常便捷的方法供我们直接调用,其中split()方法就是我们经常使用的方法之一,而今天要纠正一个之前的一个小误解。首先,先要说明一下split()方法的功能以及使用方法。
.split(String args):此方法适用于字符串的分割,参数则为分割的条件,例如:
//定义一个字符串
String string = “dog,cat,bird,tiger,elephant”;
/*
现在要将这个字符串中的“,”去掉,得到各个动物的单独的单词并存储在一个字符串数组中,
就可以调用Java提供的split()方法来实现,即,将“,”作为分割的标志,将字符串分隔开。
*/
String[ ] new_string = string.split(“,”);
// Test the result
System.out.println(new_string[ 0 ]);
System.out.println(new_string[ 1 ]);
System.out.println(new_string[ 2 ]);
System.out.println(new_string[ 3 ]);
System.out.println(new_string[ 4 ]);
//Output:
dog
cat
bird
tiger
elephant
我们都知道,在Java中的文件中,制表符(即,tab键)是以“\t”的形式存在,但我们在以文件中的空格符作为分割标志时,语句:
string.split(“\t“);是否可以得到正确的结果呢?来测试一下:
//Test the method of split
public static void main(String [] args) {
String s = "in the air";
String a[] = s.split("\t");
System.out.println(a[1]);
}
//Output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at P1.poet.GraphPoet.main(GraphPoet.java:179)
结果显示出了错误信息,而这条错误信息是说数组溢出,即,我想要看的下标为1的内容并不存在,因此可以得到数组a中的元素只有一个,那就是“in the air”,并没有将字符分隔开,没有达到我们预想的结果。理论上,制表符为“\t”,此程序并没有语法错误,接下来我们将程序稍作修改,再做一个测试:
public static void main(String [] args) {
String s = "in the air";
String a[] = s.split(" ");//将空格符改为“ ”
System.out.println(a[0]);
System.out.println(a[1]);
System.out.println(a[2]);
}
//Output:
in
the
air
结果正确,达到了我们预想的结果,将“in the air”分割成了三个单词并存储在了字符串数组a中。
因此,当我们调用split()方法,当其中的字符为空格时,要区分文件中空格的形式,若其中为制表符,则分割条件为“\t”,若文件中并没有做处理,其中单词间的空格就是空格符,则分割条件为“ ”。若没有分清楚这两个符号,则会造成错误的结果。