【问题标题】:Java String with no characters("") Split with comma returns array size 1不带字符的 Java 字符串 ("") 用逗号拆分返回数组大小 1
【发布时间】:2017-08-17 09:51:11
【问题描述】:

我有一个带有“”(空白数据)的字符串,每当我尝试用逗号分割字符串时,我都会得到一个大小为 1 的列表。

当字符串没有对象时,为什么我会得到大小为 1 的列表。

代码:

String abc = "";
String[] t = abc.split(",");
System.out.println(t.length);

输出:

1

【问题讨论】:

    标签: java arrays string split


    【解决方案1】:

    因为它需要有一个地方放置"" 条目。 split 不是有损操作(除了丢失分隔符)。

    来自the split documentation

    此方法返回的数组包含此字符串的每个子字符串,这些子字符串由与给定表达式匹配的另一个子字符串终止或以字符串结尾终止。数组中的子字符串按照它们在此字符串中出现的顺序排列。 如果表达式与输入的任何部分都不匹配,则结果数组只有一个元素,即这个字符串。

    如果在此字符串的开头存在正宽度匹配,则在结果数组的开头包含一个空的前导子字符串。但是,开头的零宽度匹配永远不会产生这样的空前导子字符串。

    (我的重点)

    【讨论】:

      【解决方案2】:

      如果你在jdk内部调试split方法的代码,你会发现这行是从它返回的地方,

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

      正如评论所说,它返回一个包含 this 的数组,在这种情况下 this 是一个空白字符串,因此您会得到一个大小为 1 的数组,其中第一个元素为空白,即 this

      在这个类似的例子中,它返回的不是空白,

      String abc = "abcd";
      String[] t = abc.split(",");
      System.out.println(t[0]); // prints "abcd" i.e this
      

      简答: // 如果没有找到匹配,返回这个

      【讨论】:

        【解决方案3】:

        这是java官方文档中写的。

         * The array returned by this method contains each substring of this
         * string that is terminated by another substring that matches the given
         * expression or is terminated by the end of the string.  The substrings in
         * the array are in the order in which they occur in this string.  If the
         * expression does not match any part of the input then the resulting array
         * has just one element, namely this string.
        

        所以这意味着每个子字符串(您放置在数组中的元素)都由另一个子字符串或字符串的结尾终止,因此它的大小为 1。

        希望这有助于消除您的疑虑。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-08-24
          • 2011-04-16
          • 1970-01-01
          • 2019-06-13
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多