Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string with specified separator without omitting empty elements

Tags:

java

string

split

Right now I am using

StringUtils.split(String str, char separatorChar)

to split input string with specified separator (,).

Example input data:

a,f,h

Output

String[] { "a", "f", "h" }

But with following input:

a,,h

It returns just

String[] { "a", "h" }

What I need is just empty string object:

String[] { "a", "", "h" }

How can I achieve this?

like image 398
hsz Avatar asked Jun 01 '11 11:06

hsz


2 Answers

If you are going to use StringUtils then call the splitByWholeSeparatorPreserveAllTokens() method instead of split().

like image 196
jzd Avatar answered Oct 01 '22 00:10

jzd


You can just use the String.split(..) method, no need for StringUtils:

"a,,h".split(","); // gives ["a", "", "h"]
like image 31
Waldheinz Avatar answered Oct 01 '22 00:10

Waldheinz