Split by character | does not return all expected elements

4

I have a file with similar lines as the following:

42|a|b|c|d||f||h|||||||||||||||||||

I need to split by character | so my code does as follows:

String linha42 = "42|a|b|c|d||f||h|||||||||||||||||||";
String[] campos = linha42.split(Pattern.quote("|"));

for(String item : campo){
    System.out.println("item: " + item);
}

But when I go through the fields he stops the split in the letter h, as if he does not recognize the others.

Output Ex:

item: 42
item: a
item: b
item: c
item: d
item: 
item: f
item: 
item: h

Any suggestions?

    
asked by anonymous 02.03.2016 / 21:58

1 answer

6

According to the documentation of split , just pass a negative integer as the second parameter of the call to receive as many results as possible (which, in the end, is what you want).

So, it would look like this:

String linha42 = "42|a|b|c|d||f||h|||||||||||||||||||";
String[] campos = linha42.split(Pattern.quote("|"), -1);

for(String item : campos){
    System.out.println("item: " + item);
}
    
02.03.2016 / 22:10