Split by the | character does not return all expected elements

Asked

Viewed 73 times

4

I have a file with lines similar to the one below:

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

I need to split by character | then my code does it like this:

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 splitting the letter h, as if he didn’t recognize the others.

Output ex:

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

Any suggestions ?

  • You need empty characters to appear on all those coming after h?

  • Yes, even if there’s nothing between the | I need to identify.

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, at bottom, 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);
}
  • 1

    It worked perfectly with this negative value solution, thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.