Home > Java > javaTutorial > How Can Java's String `split()` Method Be Used to Retrieve All Values, Including Empty Ones?

How Can Java's String `split()` Method Be Used to Retrieve All Values, Including Empty Ones?

DDD
Release: 2025-01-04 10:54:34
Original
963 people have browsed it

How Can Java's String `split()` Method Be Used to Retrieve All Values, Including Empty Ones?

Retrieving Non-Empty Values with Java's String Split Method

When splitting a string using the split() method, it's essential to understand how it handles empty values. By default, this method removes trailing empty string values from the resulting array.

To illustrate this behavior, consider the following code:

String data = "5|6|7||8|9||";
String[] split = data.split("\|");
System.out.println(split.length);
Copy after login

The expected result is an array with eight elements, including empty strings at the locations denoted by double pipe characters (||). However, only six values are obtained: [5,6,7,8,9].

Overriding the Default Behavior

To retrieve non-empty values, use the overloaded version of the split() method that takes a limit parameter set to a negative value:

String[] split = data.split("\|", -1);
Copy after login

By setting the limit to a negative value (-1 in this case), the pattern is applied as many times as possible, and the array includes all matching and non-matching values, regardless of whether or not they are empty.

Understanding the Documentation

The documentation for the split() method provides valuable insights into its behavior:

  • If the limit is greater than zero: The array's last entry contains all input beyond the last matched delimiter.
  • If the limit is non-positive: The pattern is applied as many times as possible, and the array can have any length.
  • If the limit is zero: Trailing empty strings are discarded.

Exception to the Rule

It's important to note that removing trailing empty strings only applies to those created by the split mechanism. Strings that are empty before splitting are considered original strings and are not removed.

The above is the detailed content of How Can Java's String `split()` Method Be Used to Retrieve All Values, Including Empty Ones?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template