split方法如何计算数组

时间:2014-08-04 04:26:37

标签: java string split

我有这个程序

    String s = "aa";
    String[] tokens = s.split("a");
    System.out.println(tokens.length);

它会打印0

现在当我将String更改为"aa aaaa"时,这只会打印 3 ,但为什么?它应该是6?

当我在"aa aaaa "之后添加空格时,它将打印7,这是期望值。

那么为什么split方法的行为如此?

2 个答案:

答案 0 :(得分:2)

正如split method的文件所说:

 Trailing empty strings are therefore not included in the resulting array. 

(尾随空字符串)也可以参考您提供的正则表达式,例如:a,表示所有尾随 a不会出现在结果数组中。

让我们看看它是如何拆分的

"aa"

将打印0,因为它是尾随

"aa a"

将打印3

现在当你添加空格时,它不会再a跟踪一个字符串,现在该字符串将被分割 在a之间从第一个索引开始到已知的尾随a

"aa aaaa"

仍然打印3,因为aaaa是一个尾随a

"aa aaaa "

将打印7

现在又不再是a,因此会在a's之间分割

答案 1 :(得分:0)

来自Java documentation

Splits this string around matches of the given regular expression. This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.

实施例: -

例如,字符串boo:and:foo会产生以下结果:

Regex Result : { "boo", "and", "foo" } o { "b", "", ":and:f" }

因此将丢弃所有尾随a。要进行完整拆分,返回每个元素: -

    String s = "aa";
    String[] tokens = s.split("");
    System.out.println(tokens.length); //this will output 3 :- "","a","a"