4

I want to split a String by delimiter "|" in Java and get the String array, here is my code:

String str = "123|sdf||";
String[] array = str.split("\\|");

I will get the array with 2 elements: "123","sdf". I expect the array have 4 elements: "123","sdf","",""; is there any existing class I can use to do that? I also tried StringTokernizer, doesn't work

fudy
  • 1,540
  • 5
  • 25
  • 41

1 Answers1

8

The split() method has a secret, optional 2nd parameter!

String[] array = str.split("\\|", -1); // won't discard trailing empty elements

By default, split() (with one parameter) discards trailing empty elements from the result.

If the second parameter is provided, this default discarding behaviour is turned off and if positive limits the number of elements extracted (but will return less than this if less elements found), or if negative returns unlimited elements.

Read about it in the javadoc.

Bohemian
  • 412,405
  • 93
  • 575
  • 722