hsz
hsz

Reputation: 152304

Split string with specified separator without omitting empty elements

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?

Upvotes: 8

Views: 11169

Answers (5)

Setu Poddar
Setu Poddar

Reputation: 61

Split string with specified separator without omitting empty elements.

Use the method org.apache.commons.lang.StringUtils.splitByWholeSeparatorPreserveAllTokens()

Advantage over other method's of different class :

  • It does not skip any sub-string or empty string and works fine for all char's or string as delimiter.
  • It also has a polymorphic form where we can specify the max number of tokens expected from a given string.

String.Split() method take's regex as parameter, So it would work for some character's as delimiter but not all eg: pipe(|),etc. We have to append escape char to pipe(|) so that it should work fine.

Tokenizer(String or stream) - it skips the empty string between the delimiter's.

Upvotes: 1

aioobe
aioobe

Reputation: 421310

The ordinary String.split does what you're after.

"a,,h".split(",")  yields  { "a", "", "h" }.

ideone.com demonstration.

Upvotes: 3

jzd
jzd

Reputation: 23639

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

Upvotes: 12

Waldheinz
Waldheinz

Reputation: 10497

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

"a,,h".split(","); // gives ["a", "", "h"]

Upvotes: 8

Algorithmist
Algorithmist

Reputation: 6695

You could use this overloaded split()

public String[] split(String regex,
                  int limit)

The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter

For more visit split

Upvotes: 5

Related Questions