2013-05-06 35 views
2

例子:爲什麼String.split以不同的方式處理字符串的開始和結束部分?

String s = ":a:b:c:"; 
s.split(":"); 
// Output: [, a, b, c] 

從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.

爲什麼被認爲是開始空字符串在結尾空字符串是不是? 開始的空字符串以「:」結尾,結尾的空字符串以字符串結尾終止。所以兩者都應該列出,如果他們不是?

+0

'split'確實需要一個正則表達式..所以只是':'可能不適合您的情況 – 2013-05-06 17:05:42

回答

6

當您不提供limit時,split方法不會返回尾隨空匹配項。引用Javadoc:

將此字符串拆分爲給定正則表達式的匹配。 此方法的工作原理與通過使用 給定表達式和零極限參數調用雙參數拆分方法相同。尾隨空的 字符串因此不包含在結果數組中。

如果使用的split 2參數的版本,然後通過在負極限和返回的數組的大小不會受到限制;你會得到尾隨的空字符串。

如果n是非正值,那麼該模式將被應用多次,其數量可能爲 ,並且該數組可以具有任意長度。

在這裏,我認爲Javadocs當他們說n指的是limit

0

在這種方法中尾隨空字符串將被丟棄。 你可以從here

2

詳細的想法如JavaDoc中指出:

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

.split還支持第二個參數(限制),從而改變默認行爲,如下圖所示:

String s = ":a:b:c:"; 
s.split(":", 0); //"Default" Split behaviour --> [, a, b, c] 
s.split(":", 1); //Array length == 1 --> [:a:b:c:] 
s.split(":", 2); //Array length == 2 --> [, a:b:c:] 
s.split(":", 3); //Array length == 3 --> [, a, b:c:] 
s.split(":", -1); //Any length. Trailling empty spaces are not ommited --> [, a, b, c, ] 

正如一個附註,Google Guava提供了很多類來加快在Java中的開發,如Splitter,它可以滿足您的需求:

private static final Splitter SPLITTER = Splitter.on(':') 
    .trimResults() 
    .omitEmptyStrings(); 

//returns ["a", "b", "c"] 
SPLITTER.split(":a:b::::c:::") 
相關問題