`
messi_18
  • 浏览: 96378 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

String.split

    博客分类:
  • java
 
阅读更多
String.split(String reg)这个方法一点不陌生。经常用:
"a|b|c".split("\\|")

结果是:
["a","b","c"]

但是,如果改一下输入参数呢?
"a|b|".split("\\|")

结果是:
["a","b"]


这是你想要的吗?如果是,我不废话了。如果不是,那怎么办呢?
反正这不是我想要的,我想要:
["a","b",""]

我绕了一大圈子:我去找apache commons中有没有这样的实现,没有找到。于是我开始自己写一个:
static String[] newsplit(String str) {
        if (str == null || str.length() == 0) {
            return new String[0];
        }
        
        List<Integer> indexes = new LinkedList<Integer>();
        indexes.add(-1);
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) == '|') {
               indexes.add(i);
            }
        }
        
        indexes.add(str.length());
        
        List<String> list = new LinkedList<String>();
        for (int i = 0; i < indexes.size()-1; i++) {
            list.add(str.substring(indexes.get(i)+1,indexes.get(i+1)));
        }
        
        return list.toArray(new String[0]);
    }

我自以为可以了。于是开始测试这个方法,我用了一个复杂点的例子"a||b|c|"。还好JUnit绿了。好兴奋啊。这时候,我想不明白为何JDK不提供这么简单的实现,于是我又试了下:
"a||b|c|".split("\\|")
结果是:
["a","","b","c"]

结尾的那一项还是没了,但是中间的那个空字符串竟然还在。不会吧!难道?!我打开了jdk的api的页面。看到了还有这样一个方法:Pattern.split(CharSequence,int)。然后看到了这样一段话:
The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter. If n is non-positive then the pattern will be applied as many times as possible and the array can have any length. If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.

然后,我试了下
"a||b|c|".split("\\|",-1)
结果就是我想要的。一刹那我想撞墙。为什么,一开始不仔细在jdk中先看看啊。

反思:
1>当你遇到一个问题,最优的解决方式就在最近的地方。
2>熟悉api是非常重要的。
3>不要手贱。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics