Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java String with delimiter [duplicate]

Tags:

java

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

like image 640
fudy Avatar asked Feb 13 '23 19:02

fudy


1 Answers

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.

like image 61
Bohemian Avatar answered Feb 22 '23 23:02

Bohemian