Java: String.split omits trailing empty strings 

Joined:
04/09/2007
Posts:
773

September 04, 2008 18:34:25    Last update: July 14, 2011 07:31:48
The one argument version of String.split omits trailing empty strings. To get all parts, including trailing empty strings, you need to use the two argument version with a negative limit:
public class TestStringSplit {
    public static void main(String[] args) throws Exception {
        String s = "1,2,,,,,,3 4 5,,,,,,";

        // one argument split, trailing empty strings are omitted.
        String[] a = s.split(",");
        System.out.println("Length of array: " + a.length);
        for (int i = 0; i < a.length; i++) {
            System.out.println("Part[" + i + "]: '" + a[i] + "'");
        }

        // use negative second argument to get all parts, including empty ones
        // at the end.
        a = s.split(",", -1);
        System.out.println("\n======\nLength of array: " + a.length);
        for (int i = 0; i < a.length; i++) {
            System.out.println("Part[" + i + "]: '" + a[i] + "'");
        }
    }
}

Output:
Length of array: 8
Part[0]: '1'
Part[1]: '2'
Part[2]: ''
Part[3]: ''
Part[4]: ''
Part[5]: ''
Part[6]: ''
Part[7]: '3 4 5'

======
Length of array: 14
Part[0]: '1'
Part[1]: '2'
Part[2]: ''
Part[3]: ''
Part[4]: ''
Part[5]: ''
Part[6]: ''
Part[7]: '3 4 5'
Part[8]: ''
Part[9]: ''
Part[10]: ''
Part[11]: ''
Part[12]: ''
Part[13]: ''
Share |
| Comment  | Tags