I am trying to split a string into 29 tokens..... stringtokenizer won't return null tokens. I tried string.split, but I believe I am doing something wrong:
String [] strings = line.split(",", 29);
sample inputs:
10150,15:58,23:58,16:00,00:00,15:55,23:55,15:58,00:01,16:03,23:58,,,,,16:00,23:22,15:54,00:03,15:59,23:56,16:05,23:59,15:55,00:01,,,,
10155,,,,,,,,,,,07:30,13:27,07:25,13:45,,,,,,,,,,,07:13,14:37,08:01,15:23
10160,10:00,16:02,09:55,16:03,10:06,15:58,09:48,16:07,09:55,16:00,,,,,09:49,15:38,10:02,16:04,10:00,16:00,09:58,16:01,09:57,15:58,,,,
StringTokenizer class allows you to break a String into tokens. It is simple way to break a String. It is a legacy class of Java. It doesn't provide the facility to differentiate numbers, quoted strings, identifiers etc.
A token is returned by taking a substring of the string that was used to create the StringTokenizer object. StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code.
In order to break String into tokens, you need to create a StringTokenizer object and provide a delimiter for splitting strings into tokens. You can pass multiple delimiters e.g. you can break String into tokens by, and: at the same time. If you don't provide any delimiter then by default it will use white-space.
StringTokenizer is a legacy class (i.e. there is a better replacement out there), but it's not deprecated.
If you want the trailing empty strings to be kept, but you don't want to give a magic number for maximum, use a negative limit:
line.split(",", -1)
If line.equals("a,,c")
, then line.split(",", -1)[1].isEmpty()
; it's not null
. This is because when ","
is the delimiter, then ",,"
has an empty string between the two delimiters, not null
.
Using the explanation above, consider the following example: ",,"
Although you might expect ","
, null
, and ","
.
The actual result is ","
, ""
and ","
null
instead of empty strings in the array returned by split
, then you'd have to manually scan the array and replace them with null
. I'm not sure why s == null
is better than s.isEmpty()
, though.
String.indexOf
and empty stringsUse StringUtils.splitPreserveAllTokens()
in Apache Commons Lang library
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With