Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java split by a successive character

Tags:

java

string

split

I have the following example, to explain better what i'm trying to do:

String text = "a,b,,,,c,,";
String[] split = text.split(",");
for(int i=0;i<split.length;i++){
    System.out.println("I = "+i+" "+split[i]);
}

The output is:

I = 0 a

I = 1 b

I = 2 

I = 3 

I = 4 

I = 5 c

But, what i want is to get an array of size 8, containing also:

I = 6 

I = 7

Of course, the last 2 elements will be empty strings, but it is essential for me to get them. Also, i think it's logical to have them. I mean, if i had:

String text = "a,b,,,,c,,d";

The result would be an array of size 8 and i don't think there is a big difference between the 2 examples.

like image 289
Anakin001 Avatar asked Feb 27 '13 13:02

Anakin001


1 Answers

String[] split = text.split(",", -1);

This behavior actually looks tricky but it is actually explained (not very well IMHO, that said) in the official documentation.

If n is non-positive then the pattern will be applied as many times as possible and the array can have any length

The problem with text.split(",") is that it's equivalent to text.split(",", 0). Using a 0 limit, as explained in the documentation:

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.

You definitely do not want the empty strings to be discarded.

like image 100
m0skit0 Avatar answered Nov 08 '22 08:11

m0skit0