Java String delimited

I want to split the string into delimiter "|" in Java and get an array of String, here is my code:

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

I'll get an array with two elements: "123","sdf". I expect the array has 4 elements "123","sdf","","":; Is there any existing class that I can use for this? I also tried StringTokernizer, not working

+4
source share
1 answer

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

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

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

, , ( , ), .

javadoc.

+8

Source: https://habr.com/ru/post/1526871/


All Articles