开发者

Java字符串split方法的坑及解决

目录
  • Java字符串split方法
  • Java字符串split方法的探究
  • 总结

Java字符串split方法

先来看几行简单的Java代码,如下:

System.out.println("1,2".split(",").length);
System.out.println("1,2,".split(",").length);
System.out.println("".split(",").length);
System.out.println(",".split(",").length);

接下来,猜一下各行的输出结果。OK,下面给出真正的运行结果:

2

2

1

0

这里先给出jdk相关源码,再来对应分析各自的输出:

public String[] split(String regex, int limit) {
  /* fastpath if the regex is a
  (1)one-char String and this character is not one of the
    RegEx's meta characters ".$|()[{^?*+\\", or
  (2)two-char String and the first char is the backslash and
    the second is not the ascii digit or ascii letter.
  */
  char ch = 0;
  if (((www.devze.comregex.value.length == 1 &&
    ".$|()[{^?*+\\".indexOf(ch = regex.charAt(0)) == -1) ||
    (regex.length() == 2 &&
     regex.charAt(0) == '\\' &&
     (((ch = regex.charAt(1))-'0')|('9'-ch)) < 0 &&
     ((ch-'a')|('z'-ch)) < 0 &&
     ((ch-'A')|('Z'-ch)) < 0)) &&
    (ch < Character.MIN_HIGH_SURROGATE ||
    ch > Character.MAX_LOW_SURROGATE))
  {
    int off = 0;
    int next = 0;
    boolean limited = limit > 0;
    ArrayList<String> list = new ArrayList<>();
    while ((next = indexOf(ch, off)) != -1) {
      if (!limited || list.size() < limit - 1) {
        list.add(substring(off, next));
        off = next + 1;
      } else {  // last one
        //assert (list.size() == limit - 1);
        list.add(substring(off, value.length));
        off = value.length;
        break;
      }
    }
    // If no match was found, return this
    if (off == 0)
      return new String[]{this};

    // Add remaining segment
    if (!limited || list.size() < limit)
      list.add(substring(off, value.length));

    // Construct result
    int resultSize = list.size();
    if (limit == 0) {
      while (resultSize > 0 && list.get(resultSize - 1).length() == 0) {
        resultSize--;
      }
    }
    String[] result = new String[resultSize];
    return list.subList(0, resultSize).toArray(result);
  }
  return Pattern.compile(regex).split(this, limit);
}

1.第一行代码的输出结果肯定没什么问题,字符串 "1,2" 以 "," 分隔,结果很直观的是 ["1", "2"],length=2。

2.第二行代码的输出结果,可能大家有人认为是length=3才对,因为字符串 "1,2," 以 "," 分隔,结果应该是 ["1", "2", ""],length=3;其实不然,jdk在split处理的时候,确实会先生成一个集合list = ["1", "2", ""],但之后却会循环判断末位元素是否为空字符串(即末位元素length=0),因此集合最终会变成 ["1", "2"],length=2。具体判断如下:

while (resultSize > 0 && list.get(resultSize - 1).length() == 0) {
  resultSize--;
}

3.第三行代码的输出结果,数组 [""],length=1。与其他三种情况不同,空字符串 "" 中不包含regex字符串 ",",所以代表没有匹配上的子串(off=0),则返回字符串本身。具体处理如下:

// If no match was found, return this
if (off == 0)
  return new String[]{this};

4.第四行代码的输出结果,可能也有部分人认为结果应是length=2,因为字符串 "," 以 "," 分隔,结果应该是 ["", ""],length=2;其实亦不然,与第2行同样的原理,最终将list=["", ""] 处理为空集合 [],length=0。

以上,系本文分享的split的一个小坑;除此之外,另一个需要注意的地方,split方法的参数是正则表达式而非一般字符串,所以在处理正则转义字符和特殊字符时留意即可。

Java字符串split方法的探究

今天在使用split分割字符串时突然想到一种情况,如下:

String str="aaaaaaaab";
String arr[]=str.split("aa")www.devze.com;

问,arr数组的长度是多少?

那如果str为”baaaaaaaa”呢

String str="baaaaaaaa";

如果str=”aaaaaaaab”呢

String str="aaaaaaaab";

如果str=”baaaaaaaab”呢

String str="baaaaaaaab";

好,我们先在程序中验证一下:

public class Test {

	public static void main(String[] args) {
		String str="aaaaaaaa";
		String [] arr=str.split("aa");
		System.out.println("字符串aaaaaaaa分割的数组长度为:"+arr.length);
		
		str="baaaaaaaa";
		arr=str.split("aa");
		System.out.println("字符串baaaaaaaa分割的数组长度为:"+arr.length);
		
		str="aaaaaaaab";
		arr=str.split("aa");
		System.out.println("字符串aaaaaaaab分割的数组长度为:"+arr.length);
		
		str="baaaaaaaab";
		arr=str.split("aa");
		System.out.println("字符串baaaaaaaab分割的数组长度为:"+arr.length);

	}
}

运行以上代码输出结果

Java字符串split方法的坑及解决

看到结果的你是不是有点小小的惊讶,如果有的话那就继续往下看。

通过split方法查看源码可知又调用了split(regex, 0)方法并且传入一个0:

  public String[] split(String regex) {
        return split(regex, 0);
    }

继续查看源码

 public String[] split(String regex, int limit) {
        /* fastpath if the regex is a
         (1)one-char String and this character is not one of the
            RegEx's meta characters ".$|()[{^?*+\\", or
         (2)two-char String and the first char is the backslash and
            the second is not the ascii digit or ascii letter.
         */
        char ch = 0;
        if (((regex.value.length == 1 &&
             ".$|()[{^?*+\\".indexOf(ch = regex.charAt(0)) == -1) ||
             (regex.length() == 2 &&
              regex.charAt(0) == '\\' &&
              (((ch = regex.charAt(1))-'0')|('9'-ch)) < 0 &&
              ((ch-'a')|('z'-ch)) < 0 &&
              ((ch-'A')|('Z'-ch)) < 0)) &&
            (ch < Character.MIN_HIGH_SURROGATE ||
             ch > Character.MAX_LOW_SURROGATE))
        {
            int off = 0;
            int next = 0;
            boolean limited = limit > 0;
            ArrayList<String> list = new ArrayList<>();
            while ((next = indexOf(ch, off)) != -1) {
                if (!limited || list.size() < limit - 1) {
                    list.add(substring(off, next));
                    off = next + 1;
                } else {    // last one
                    //assert (list.size() == limit - 1);
                    list.add(substring(off, value.length));
                    off = value.length;
                    break;
                }
            }
            // If no match was found, return this
            if (off == 0)
                return new String[]{this};

            // Add remaining segment
            if (!limited || list.size() < limit)
                list.add(substring(off, value.length));

            // Construct result
            int resultSize = list.size();
            if (limit == 0) {
                while (resultSize > 0 && list.get(resultSize - 1).length() == 0) {
                    resultSize--;
                }
            }
            String[] result = new String[resultSize];
            return list.subList(0, resultSize).toArray(result);
        }
        return Pattern.compile(regex).split(this, limit);
    }

有其中关系可知最终会执行 Pattern.compile(regex).split(this, limgyDJCkNPSgit)这一段代码,基础往下扒代码:

  public String[] split(CharSequence input, int limit) {
        int index = 0;
        boolean matchLimited = limit > 0;
        ArrayList<String> matchList = new ArrayList<>();
        Matcher m = matcher(input);

        // Add segments before each match found
        while(m.find()) {
            if (!matchLimited || matchList.size() < limit - 1) {
                if (index == 0 && index == m.start() && m.start() == m.end()) {
                    // no empty leading substring included for zero-width match
                    // at the beginning of the input char sequence.
               android     continue;
                }
                String match = input.subSequence(index, m.start()).toString();
                matchList.add(match);
                index = m.end();
            } else if (matchList.size() == limit - 1) { // last one
                String match = input.subSequence(index,
                                                 input.lephpngth()).toString();
                matchList.add(match);
                index = m.end();
            }
        }

        // If no match was found, return this
        if (index == 0)
            return new String[] {input.toString()};

        // Add remaining segment
        if (!matchLimited || matchList.size() < limit)
            matchList.add(input.subSequence(index, input.length()).toString());

        // Construct result
        int resultSize = matchList.size();
        if (limit == 0)
            while (resultSize > 0 && matchList.get(resultSize-1).equals(""))
                resultSize--;
        String[] result = new String[resultSize];
        return matchList.subList(0, resultSize).toArray(result);
    }

通过代码我们可以发现最终matchList集合中会有值,不过都是空值,然后在

  while (resultSize > 0 && matchList.get(resultSize-1).equals(""))
                resultSize--;开发者_Js入门

这一段代码中,首先判断最后一个是不是空,如果没有值的话就减一位,依次类推,所以看到这大家对以上程序出现的结果是不是就不奇怪了。

所以我们可以大胆的总结一下,使用split方法分割字符串,如果最后几位是空的话,会将空的位置去掉。

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新开发

开发排行榜