8

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?

5 Answers 5

12

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

Sign up to request clarification or add additional context in comments.

Comments

8

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

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

1 Comment

Note that String.split will still omit empty strings from the end of the array, e.g., "a,h,".split(",") gives ["a","h"], not ["a","h",""]. To get the empty strings from the end, you can supply a negative number as the second argument to split. (docs.oracle.com/javase/6/docs/api/java/lang/…) Sometimes Java is weird...
5

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

Comments

3

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

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

ideone.com demonstration.

Comments

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.