I need help using split()
to split string into array java
. Given the string:
String values = "0|0|0|1|||0|1|0|||";
I want to store the values in an array, where possible values are "0"
, "1"
, and ""
.
However, when I use:
String[] array = values.split("\\|");
The values are only saved until the last 0
, and the "|||"
at the end seems to be trimmed.
What am I doing wrong, and how can I ensure empty values are preserved?
Use split()
with a Negative Limit
If you want to split string into array java and retain empty values, especially the trailing ones, pass -1
as the limit:
String values = "0|0|0|1|||0|1|0|||";
String[] array = values.split("\\|", -1);
Why it works:
Java’s split()
trims trailing empty strings by default—but with -1
as the limit, it keeps all values, even if they’re empty.
So "|||"
at the end doesn’t get lost; it turns into ["", "", ""]
just as expected.
Use StringTokenizer
for Detailed Handling
When you need to split string into array java and handle each delimiter more delicately, go for StringTokenizer
:
import java.util.StringTokenizer;
import java.util.ArrayList;
import java.util.List;
String values = "0|0|0|1|||0|1|0|||";
StringTokenizer tokenizer = new StringTokenizer(values, "|", true);
List<String> result = new ArrayList<>();
boolean lastWasDelimiter = false;
while (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
if (token.equals("|")) {
if (lastWasDelimiter) result.add("");
lastWasDelimiter = true;
} else {
result.add(token);
lastWasDelimiter = false;
}
}
String[] array = result.toArray(new String[0]);
Why this rocks:
- Retains empty values between and around delimiters
- Lets you build exactly the structure you want, with full control over parsing logic
Manually Append Missing Values When Needed
If you split string into array java using the regular split("\\|")
, but find it trims too much, try this hybrid approach:
String[] array = values.split("\\|", -1);
if (values.endsWith("|")) {
int expectedSize = values.split("\\|").length + 1;
array = Arrays.copyOf(array, expectedSize);
}
Why bother?
- It keeps the syntax familiar
- You still get those trailing empty values without overhauling the code
- Great workaround when you’re dealing with legacy methods or restricted APIs