zoukankan      html  css  js  c++  java
  • 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","",""}的原因所在了。

  • 相关阅读:
    设计模式-11-代理模式
    设计模式-10-装饰者
    设计模式-9-组合
    设计模式-8-适配器
    设计模式-7-原型模式
    设计模式-6-建造者
    设计模式-5-单例模式
    u-boot-1.1.6 设置新分区支持设备树
    u-boot-2014.10移植(8)重定位,支持NAND启动
    u-boot-2014.10移植(7)修改环境变量的存储位置
  • 原文地址:https://www.cnblogs.com/xzhang/p/3995464.html
Copyright © 2011-2022 走看看