Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java split function gives me a small length of result String array

Tags:

java

string

split

I have this code:

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

The result is that variable parts has only three elements

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

This is weird, because there are five "_" chars, so after splitting there should be six elements, not only three of them.

I want

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

How to do that? Thank you very much!

like image 651
J. Neal Avatar asked Dec 24 '22 17:12

J. Neal


1 Answers

From Java documentation:-

Trailing empty strings are therefore not included in the resulting array.

Trysplit("_",6)

like image 99
Zakir Avatar answered Jan 11 '23 23:01

Zakir