The Java split function gives me a short result length. String array

I have this code:

String string = "_a_b___";
String[] parts = string.split("_");

As a result, the variable parts have only three elements

parts[0] = ""
parts[1] = "a" 
parts[2] = "b"

This is strange because there are five "_" characters, so after splitting there should be six elements, not just three of them.

I want to

parts[0] = ""
parts[1] = "a"
parts[2] = "b"
parts[3] = ""
parts[4] = "" 
parts[5] = "" 

How to do it? Thank you very much!

+4
source share
2 answers

From Java Documentation : -

Thus, trailing blank lines are not included in the array.

Try split("_",6)

+6
source

@Zakir , , , , , split("_", 6), :

String[] parts = string.split("_", string.replace("(?!_)", "").length());

.

_a_b___ [, a, b, , , ]


Edit

@Bill F , String[] parts = string.split("_", -1); . Java doc

+4

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


All Articles