Home > Java > javaTutorial > How Can I Preserve Empty Strings When Splitting Strings in Java?

How Can I Preserve Empty Strings When Splitting Strings in Java?

Barbara Streisand
Release: 2024-12-28 04:59:09
Original
155 people have browsed it

How Can I Preserve Empty Strings When Splitting Strings in Java?

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);
Copy after login

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);
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template