其中separator表示分隔符,limit表示返回数组的元素个数
注意:
separator中如果有“.”和“|”转义字符时前面必须加\\:
如果用“.”作为分隔的话,必须是如下写法:String.split("\\."),这样才能正确的分隔开,不能用String.split(".");
如果用“|”作为分隔的话,必须是如下写法:String.split("\\|"),这样才能正确的分隔开,不能用String.split("|");
如果在一个字符串中有多个分隔符,可以用“|”作为连字符,比如:“a=1 and b =2 or c=3”,把三个都分隔出来,可以用String.split("and|or");
limit分组时是对整个字符串分组,分组后的元素包含原来String字符串里的所有字符!如下面的示例2:
示例1:
public class SplitDemo {
public static String[] ss=new String[20];
public SplitDemo() {
String s = "The rain in Spain falls mainly in the plain.";
// 在每个空格字符处进行分解。
ss = s.split(" ");
}
public static void main(String[] args) {
SplitDemo demo=new SplitDemo();
for(int i=0;i<ss.length;i++)
System.out.println(ss[i]);
}
}
程序结果:
The
rain
in
Spain
falls
mainly
in
the
plain
示例2:
public class SplitDemo {public static String[] ss=new String[20];
public SplitDemo() {
String s = "The rain in Spain falls mainly in the plain.";
ss = s.split(" ",2); // 在每个空格字符处进行分解。
}
public static void main(String[] args) {
SplitDemo demo=new SplitDemo();
for(int i=0;i<ss.length;i++)
System.out.println(ss[i]);
}
}
程序结果:
The
rain in Spain falls mainly in the plain
示例3:
public class SplitDemo3 {
public static String[] ss = new String[20];
public SplitDemo3() {
String s = "The rain in Spain falls mainly in the plain.";
ss = s.split(" ", 20); // 在每个空格字符处进行分解
}
public static void main(String[] args) {
SplitDemo3 demo = new SplitDemo3();
for (int i = 0; i < ss.length; i++)
System.out.println(ss[i]);
}
}
程序结果:
The
rain
in
Spain
falls
mainly
in
the
plain.