Splitting String with Preserved Empty Values in Java
When performing string splitting using the String.split() method, an unexpected behavior occurs where consecutive delimiters result in empty values being removed from the resulting array. However, the expectation may be to retain these empty values to preserve the original order and structure of the data.
String data = "5|6|7||8|9||"; String[] split = data.split("\|"); System.out.println(split.length);
In this example, with the default "split()" method, only six values are returned: [5, 6, 7, 8, 9, EMPTY]. To retain the empty values, the overloaded version of split() that takes a limit parameter can be used. By setting the limit to a negative value, empty values are preserved.
String[] split = data.split("\|", -1);
The documentation for split(regex, limit) states that when the limit is non-positive, the pattern will be applied as many times as possible, allowing the resulting array to have any length, and that trailing empty strings will be discarded.
Exception:
It's important to note that removing trailing empty strings only makes sense if those empty strings were created during the splitting process. For example, splitting an empty string ("") with any delimiter will result in an array containing an empty string: ["", ""]. This is because there is no split to perform, so the original string itself is represented as an empty string in the array.
The above is the detailed content of How Can I Preserve Empty Strings When Splitting Strings in Java?. For more information, please follow other related articles on the PHP Chinese website!