Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why java String.split is ignoring last character is split is based on last character [duplicate]

Tags:

java

java-8

If I run the following code:

"testx".split("x")

the expectation is that we will get {"test", ""}, but instead java is returning {"test"}

But "xtest".split("x") returns {"", "test"}. Any ides why its behaving weirdly (or) do I have the wrong understanding?

Here is my JDK & system info:

JRE: 1.8.0_152-release-1024-b6 amd64

JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o

Linux 4.4.0-34-generic

like image 822
Ashok Koyi Avatar asked Feb 13 '26 23:02

Ashok Koyi


1 Answers

From String.split documentation:

This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.

If you want to preserve the trailing empty string then you can use String.split(String, int) like this:

String str = "testx";
String[] values = str.split("x", -1);

Output:

{"test", ""}
like image 159
Juan Carlos Mendoza Avatar answered Feb 16 '26 12:02

Juan Carlos Mendoza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!