Java String split() 字符串切割方法
split() 方法根据匹配给定的正则表达式来拆分字符串。
注意: . 、 $、 | 和 * 等转义字符,必须得加 \ ;多个分隔符,可以用 | 作为连字符。
语句:
public String[] split(String regex, int limit)
参数:
-
regex -- 正则表达式分隔符。
-
limit -- 分割的份数。
返回值: 字符串数组
split()方法实例:
public class Test {
public static void main(String args[]) {
String str = new String("Welcome-to-catroom");
System.out.println("- 分隔符返回值 :" );
for (String retval: str.split("-")){
System.out.println(retval);
}
System.out.println("");
System.out.println("- 分隔符设置分割份数返回值 :" );
for (String retval: str.split("-", 2)){
System.out.println(retval);
}
System.out.println("");
String str2 = new String("www.catroom.com.cn");
System.out.println("转义字符返回值 :" );
for (String retval: str2.split("\\.", 3)){
System.out.println(retval);
}
System.out.println("");
String str3 = new String("acount=? and uu =? or n=?");
System.out.println("多个分隔符返回值 :" );
for (String retval: str3.split("and|or")){
System.out.println(retval);
}
}
}
以上程序执行结果为:
- 分隔符返回值 :
Welcome
to
catroom
- 分隔符设置分割份数返回值 :
Welcome
to-catroom
转义字符返回值 :
www
catroom
com
多个分隔符返回值 :
acount=?
uu =?
n=?