How can split a string which contains only delimiter?

后端 未结 5 721
难免孤独
难免孤独 2020-12-10 12:11

I am using the following code:

String sample = \"::\";
String[] splitTime = sample.split(\":\");
// extra detail omitted
System.out.println(\"Value 1 :\"+spl         


        
5条回答
  •  情歌与酒
    2020-12-10 12:22

    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 : ""
    

提交回复
热议问题