How can split a string which contains only delimiter?

java, regex, split

Solution

Alnitak is correct that trailing empty strings will be discarded by default.

If you want to have trailing empty strings, you should use `split(String, int)` and pass a negative number as the `limit` parameter.

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.

Note that `split(aString)` is a synonym for `split(aString, 0)`:

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.

Also, you should use a loop to get the values from the array; this avoids a possible `ArrayIndexOutOfBoundsException`.

So your corrected code should be (assuming you want the trailing empty strings):

String sample = "::";
String[] splitTime = sample.split(":", -1);
for (int i = 0; i < splitTime.length; i++) {
    System.out.println("Value " + i + " : \"" + splitTime[i] + "\"");
}

Output:

Value 0 : ""
Value 1 : ""
Value 2 : ""

Problem

I am using the following code: ``` String sample = "::"; String[] splitTime = sample.split(":"); // extra detail omitted System.out.println("Value 1 :"+splitTime[0]); System.out.println("Value 2 :"+splitTime[1]); System.out.println("Value 3 :"+splitTime[2]); ``` I am getting `ArrayIndexOutofBound` exception. How does `String.split()` handle consecutive or trailing / opening delimiters? See also: - Doubt in split method - Java split() method strips empty strings at the end?

Original source