string split 空字符串問題

 

String str="123,123,,123,,";

 

System.out.println(str.split(",").length);// 這時結果會是4, 最後的2個因爲是空白沒有算

 

System.out.println(str.split(",",-1).length);//這時會是6, 是我想要的

 

爲什麼呢, 看下源碼

 

最後執行到的是

 

    public String[] split(CharSequence input, int limit) {

        int index = 0;

        boolean matchLimited = limit > 0;

        ArrayList<String> matchList = new ArrayList<String>();

        Matcher m = matcher(input);

 

        // Add segments before each match found

        while(m.find()) {

            if (!matchLimited || matchList.size() < limit - 1) {

                String match = input.subSequence(index, m.start()).toString();

                matchList.add(match);

                index = m.end();

            } else if (matchList.size() == limit - 1) { // last one

                String match = input.subSequence(index,

                                                 input.length()).toString();

                matchList.add(match);

                index = m.end();

            }

        }

 

        // If no match was found, return this

        if (index == 0)

            return new String[] {input.toString()};

 

        // Add remaining segment

        if (!matchLimited || matchList.size() < limit)

            matchList.add(input.subSequence(index, input.length()).toString());

 

        // Construct result

        int resultSize = matchList.size();

        if (limit == 0)

            while (resultSize > 0 && matchList.get(resultSize-1).equals(""))

                resultSize--;

        String[] result = new String[resultSize];

        return matchList.subList(0, resultSize).toArray(result);

    }

 

 

 

這裏

 

        if (limit == 0)

            while (resultSize > 0 && matchList.get(resultSize-1).equals(""))

                resultSize--;

 

這裏把後面的空白字符串減去了。

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章