Reputation: 152304
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
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 :
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
Reputation: 421310
The ordinary String.split
does what you're after.
"a,,h".split(",")
yields { "a", "", "h" }
.
Upvotes: 3
Reputation: 23639
If you are going to use StringUtils
then call the splitByWholeSeparatorPreserveAllTokens()
method instead of split()
.
Upvotes: 12
Reputation: 10497
You can just use the String.split(..) method, no need for StringUtils:
"a,,h".split(","); // gives ["a", "", "h"]
Upvotes: 8
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