1

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

Juan Carlos Mendoza
  • 5,736
  • 7
  • 25
  • 50
Ashok Koyi
  • 5,327
  • 8
  • 41
  • 50

1 Answers1

8

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", ""}
Juan Carlos Mendoza
  • 5,736
  • 7
  • 25
  • 50
  • Is there a way to get to force Java not to ignore end empty results? – Ashok Koyi Nov 17 '17 at 19:18
  • @Kalinga Read that piece of quoted documentation again, and then think _"what would happen if I call the two-argument split method with a value other than zero for the limit argument"_ (or consult the documentation of [that method](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#split-java.lang.String-int-)) . – Mark Rotteveel Nov 17 '17 at 19:30
  • 1
    It would be easier to just use `str.split("x", -1)` – Mark Rotteveel Nov 17 '17 at 19:32
  • @MarkRotteveel you are right. Edited. – Juan Carlos Mendoza Nov 17 '17 at 19:34
  • Why does a String containing empty space character as last character gets returned when delimitter is an empty space character " " ? Eg: `String s = "a "; public static int lengthOfLastWord(String s) { int l = 0; for(String eachWord : s.split("\\s+", -1)){ if(!eachWord.equals(" ")){ l = eachWord.length(); System.out.println("'" + eachWord + "'"); } } return l; }` returns 'a' and ' '. Whereas, if `String s = "a a";` then output is just 'a' followed by another 'a' Why is this happening in Java 8? – sofs1 Feb 01 '19 at 23:06