Java split方法源码分析

 Java split方法源码分析
 1 public String[] split(CharSequence input [, int limit]) {
 2     int index = 0;                         // 指针
 3     boolean matchLimited = limit > 0;      // 是否限制匹配个数
 4     ArrayList<String> matchList = new ArrayList<String>();  // 匹配结果队列
 5     Matcher m = matcher(input);            // 待切割字符(串)匹配对象,pattern去哪了?
 6 
 7     // Add segments before each match found
 8     while(m.find()) {
 9         if (!matchLimited || matchList.size() < limit - 1) {  // 如果不限制匹配个数 或者 当前结果列表的大小小于limit-1
10             String match = input.subSequence(index, m.start()).toString();  // 取子串,(指针位置,分隔串所在的首位)
11             matchList.add(match);      // 添加进结果集
12             index = m.end();           // 移动指针
13         } else if (matchList.size() == limit - 1) { // last one,即还剩最后一个名额了
14             String match = input.subSequence(index, input.length()).toString();  // 最后一个元素从指针取到字符串结尾
15             matchList.add(match);
16             index = m.end();
17         }
18     }
19 
20     // If no match was found, return this
21     if (index == 0)  // 即没有切分到的意思吧,返回整一串
22         return new String[] {input.toString()};
23 
24     // Add remaining segment
25     if (!matchLimited || matchList.size() < limit)  // 如果不限制匹配个数 或者 结果集大小小于限制个数
26                                                     // 这个时候,后面已无匹配,如__1_1___,取最后一个1的后面部分
27         matchList.add(input.subSequence(index, input.length()).toString());  // 最后一个元素从指针取到字符串结尾
28 
29     // Construct result
30     int resultSize = matchList.size();
31     if (limit == 0)
32         while (resultSize > 0 && matchList.get(resultSize-1).equals(""))  // 如果结果集最后的元素是"",一个一个地删除它们
33             resultSize--;
34     String[] result = new String[resultSize];
35     return matchList.subList(0, resultSize).toArray(result);
36 }


特别地,最后的while循环里,把结果集的位于最后的""元素删除了,有人问过“boo:and:foo”用“o”来分割,为什么结果是{“b”,"",":and:f"},而不是{"b","",":and:f","",""}的原因所在了。






转载:http://www.cnblogs.com/xzhang/p/3995464.html

自己实现split方式:

	public static String[] split1(String str,char char1){
		
		String [] a = new String[20];
		int k=0;
		int j=0;	
		char [] b =str.toCharArray();
		String s1 =new String();
		for(int i =0;i<b.length;i++){
			if (b[i] == char1) {				
				while (k<i){		
						s1=s1+b[k];	
						k++;
				}	
				a[j]=s1;
				j++;
				k=i+1;	
				s1="";
			}else if (i == b.length -1) { 
				while (k<i+1){		
					s1=s1+b[k];	
					k++;
				}	
				a[j]=s1;			
			}		
		}	
		return a;
	}
	







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值