Reputation: 85
In C#, if I have a string like this:
String test = ";;;;";
String[] split = test.Split(';');
Console.WriteLine(split.Length); // Then I got 5 here
But in Java:
String test = ";;;;";
String[] split = test.split(";");
System.out.println(split.length); // Then I got only 1 here
Upvotes: 2
Views: 2349
Reputation: 121830
Use:
test.split(";", -1);
This is an unfortunate design decision; by default, .split()
will trim (most) empty strings from the end of the result array.
If you want a real splitter, use Guava's Splitter
. It performs much better than the JDK's .split()
method, is unassuming and doesn't have to use a regex as an argument!
Upvotes: 6
Reputation: 285430
Try:
String test = ";;;;";
String[] split = test.split(";", -1);
System.out.println(split.length);
The String API explains this method overload that also adds a limit field.
If n is non-positive then the pattern will be applied as many times as possible and the array can have any length.
Upvotes: 9