split的作用:
将一个字符串分割为子字符串,然后将结果作为字符串数组返回。
参数说明:
String regex:
regex音译为正则表达式,简单理解就是我们用来分割字符串的一个规则。
int limit:
limit音译为限制,通俗的说就是设置返回数组元素的个数。
看代码(1):
public static void main(String[] args) { String source = "A&BC&DEF&GH";//演示字符串数据源 //设置limit=0时 String [] segment = source.split("&", 0);//分割数组数据 System.out.println("分割数组长度:"+segment.length); System.out.println("分割数组数据:"+Arrays.toString(segment)); } 输出结果: 分割数组长度:4 分割数组数据:[A, BC, DEF, GH]
看代码(2):
public static void main(String[] args) { String source = "A&BC&DEF&GH";//演示字符串数据源 //设置limit=1时 String [] segment = source.split("&", 1);//分割数组数据 System.out.println("分割数组长度:"+segment.length); System.out.println("分割数组数据:"+Arrays.toString(segment)); } 输出结果: 分割数组长度:1 分割数组数据:[A&BC&DEF&GH]
看代码(3):
public static void main(String[] args) { String source = "A&BC&DEF&GH";//演示字符串数据源 //设置limit=2时 String [] segment = source.split("&", 2);//分割数组数据 System.out.println("分割数组长度:"+segment.length); System.out.println("分割数组数据:"+Arrays.toString(segment)); } 输出结果: 分割数组长度:2 分割数组数据:[A, BC&DEF&GH]
再来做一个测试,以下测试个人觉得对我的业务有用,看下面的代码:
public static void main(String[] args) { String source = "A&BC&DEF&GH&A&BC&DEF&GH&A&BC&DEF&GH&A&BC&DEF&GH&A&BC&DEF&GH&A&BC&DEF&GH&A&BC" + "&DEF&GH&A&BC&DEF&GH&A&BC&DEF&GH&A&BC&DEF&GH&A&BC&DEF&GH&A&BC&DEF&GH&A&BC&DEF&GH&A&BC&D" + "EF&GH&A&BC&DEF&GH&A&BC&DEF&GH&A&BC&DEF&GH&A&BC&DEF&GH&A&BC&DEF&GH&A&BC&DEF&GH&A&BC&DEF&G" + "H&A&BC&DEF&GH&A&BC&DEF&GH&A&BC&DEF&GH&A&BC&DEF&GH&A&BC&DEF&GH&A&BC&DEF&GH&A&BC&DEF&GH&A&BC&DEF&GH&";//演示字符串数据源 //设置limit=2时 Long t1 = System.currentTimeMillis(); String [] segment1 = source.split("&");//分割数组数据 System.out.println("1消耗时间:"+String.valueOf(System.currentTimeMillis()-t1)); Long t2 = System.currentTimeMillis(); String [] segment2 = source.split("&", 2);//分割数组数据 System.out.println("2消耗时间:"+String.valueOf(System.currentTimeMillis()-t2)); System.out.println("分割数组长度:"+segment1.length); System.out.println("分割数组数据:"+Arrays.toString(segment1)); System.out.println("分割数组长度:"+segment2.length); System.out.println("分割数组数据:"+Arrays.toString(segment2)); } 输出结果: 1消耗时间:1 2消耗时间:0 分割数组长度:116 分割数组数据:[A, BC, DEF, GH, A, BC, DEF, GH, A, BC, DEF, GH, A, BC, DEF, GH, A, BC, DEF, GH, A, BC, DEF, GH, A, BC, DEF, GH, A, BC, DEF, GH, A, BC, DEF, GH, A, BC, DEF, GH, A, BC, DEF, GH, A, BC, DEF, GH, A, BC, DEF, GH, A, BC, DEF, GH, A, BC, DEF, GH, A, BC, DEF, GH, A, BC, DEF, GH, A, BC, DEF, GH, A, BC, DEF, GH, A, BC, DEF, GH, A, BC, DEF, GH, A, BC, DEF, GH, A, BC, DEF, GH, A, BC, DEF, GH, A, BC, DEF, GH, A, BC, DEF, GH, A, BC, DEF, GH, A, BC, DEF, GH, A, BC, DEF, GH] 分割数组长度:2 分割数组数据:[A, BC&DEF&GH&A&BC&DEF&GH&A&BC&DEF&GH&A&BC&DEF&GH&A&BC&DEF&GH&A&BC&DEF&GH&A&BC&DEF&GH&A&BC&DEF&GH&A&BC&DEF&GH&A&BC&DEF&GH&A&BC&DEF&GH&A&BC&DEF&GH&A&BC&DEF&GH&A&BC&DEF&GH&A&BC&DEF&GH&A&BC&DEF&GH&A&BC&DEF&GH&A&BC&DEF&GH&A&BC&DEF&GH&A&BC&DEF&GH&A&BC&DEF&GH&A&BC&DEF&GH&A&BC&DEF&GH&A&BC&DEF&GH&A&BC&DEF&GH&A&BC&DEF&GH&A&BC&DEF&GH&A&BC&DEF&GH&A&BC&DEF&GH&]
因为我只要第一条拆分出来的数据,所以嘿嘿,请楼下回答有什么好与坏处吧。