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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With