【问题标题】:split method of String class does not include trailing empty strings [duplicate]String 类的 split 方法不包括尾随空字符串 [重复]
【发布时间】:2010-01-31 04:35:39
【问题描述】:

可能重复:
Java split() method strips empty strings at the end?

String 类的 split 方法在其返回的数组中不包含尾随的空字符串。我该如何克服这个限制:

class TestRegex{
 public static void main(String...args){
  String s = "a:b:c:";    
  String [] pieces = s.split(":");

  System.out.println(pieces.length); // prints 3...I want 4.
 }
}

【问题讨论】:

    标签: java regex


    【解决方案1】:

    根据documentation

    这个方法就像通过调用 两参数拆分方法与 给定表达式和限制参数 零。

    对于带有限制参数的拆分,它说:

    如果 n 为非正数,则模式 将被应用多次 可能的,数组可以有任何 长度。如果 n 为零,则模式 将被应用多次 可能的,数组可以有任何 长度和尾随空字符串 将被丢弃。

    因此,尝试使用非正限制参数调用 split 方法,如下所示:

    String[] pieces = s.split(":", -1);
    

    【讨论】:

      猜你喜欢
      • 2014-03-01
      • 2019-09-22
      • 1970-01-01
      • 2020-08-27
      • 2016-12-26
      • 2010-10-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多