您的位置:首页 > 编程语言 > Java开发

JAVA学习提高之---- String.split(String,int)使用

2008-12-29 18:02 796 查看
package com.gobusiness.eus.util;

public class Test {

public static void main(String[] args){
String str = "bb:oo:and:foo";
String[] strArray;
strArray = str.split("o");
printSplit(strArray);
strArray = str.split("o",1);
printSplit(strArray);
strArray = str.split("o",2);
printSplit(strArray);
strArray = str.split("o",3);
printSplit(strArray);
strArray = str.split("o",4);
printSplit(strArray);
strArray = str.split("o",5);
printSplit(strArray);
strArray = str.split("o",7);
printSplit(strArray);

}

public static void printSplit(String[] array){
for(int i=0;i<array.length;i++){
if(array[i].equals("")){
System.out.println("^");
}else{
System.out.println(array[i]);
}
}
System.out.println("the length is :" + array.length);
System.out.println(">>>>>>end");
}
}

String (Java 2 Platform SE 5.0)

split

public String[] split(String regex,
int limit)

根据匹配给定的正则表达式来拆分此字符串。
此方法返回的数组包含此字符串的每个子字符串,这些子字符串由另一个匹配给定的表达式的子字符串终止或由字符串结束来终止。数组中的子字符串按它们在此字符串中的顺序排列。如果表达式不匹配输入的任何部分,则结果数组只具有一个元素,即此字符串。

limit 参数控制模式应用的次数,因此影响结果数组的长度。如果该限制 n 大于 0,则模式将被最多应用
n - 1 次,数组的长度将不会大于 n,而且数组的最后项将包含超出最后匹配的定界符的所有输入。如果 n
为非正,则模式将被应用尽可能多的次数,而且数组可以是任意长度。如果 n
为零,则模式将被应用尽可能多的次数,数组可有任何长度,并且结尾空字符串将被丢弃。

运行结果为:
bb:
^
:and:f
the length is :3
>>>>>>end
bb:oo:and:foo
the length is :1
>>>>>>end
bb:
o:and:foo
the length is :2
>>>>>>end
bb:
^
:and:foo
the length is :3
>>>>>>end
bb:
^
:and:f
o
the length is :4
>>>>>>end
bb:
^
:and:f
^
^
the length is :5
>>>>>>end
bb:
^
:and:f
^
^
the length is :5
>>>>>>end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: