Split a string with the specified delimiter without omitting empty elements

I'm using now

StringUtils.split(String str, char separatorChar) 

to separate the input string with the specified delimiter ( , ).

Sample input:

 a,f,h 

Exit

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

But with the following input:

 a,,h 

It only returns

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

I only need an empty string object:

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

How can i achieve this?

+7
source share
5 answers

You can simply use the String.split (..) method, without the need for StringUtils:

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

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

+11
source

You can use this overloaded split ()

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

The limit parameter controls the number of uses of the template and, therefore, affects the length of the resulting array. If the limit n is greater than zero, then the pattern will be applied no more than n - 1 times, the length of the array will be no more than n, and the last element of the array will contain all input data outside the last matched separator

Read more ... split

+4
source

Regular String.split does what you need.

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

demo of ideone.com .

+3
source

Split a string with the specified delimiter without omitting empty elements.

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

Advantage over another method of another class:

  • It does not skip any substring or empty string and works fine for all char or string as a separator.
  • It also has a polymorphic form, where we can specify the maximum number of tokens expected from a given string.

String.Split() method accepts regex as a parameter, so it will work for some character as a separator, but not for all, for example: pipe (|), etc. We need to add an escape char to pipe (|) so that it works fine.

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

+1
source

All Articles