Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
185 views
in Technique[技术] by (71.8m points)

java - How can split a string which contains only delimiter?

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:

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...