0

I have a question about java.lang.String.split().

String str = "aaaaa";
String[] str1 = str.split("a");
str = "aaaaa ";
String[] str2 = str.split("a");

System.out.println(Arrays.toString(str1));
System.out.println(Arrays.toString(str2));

Result is

str1 == null
str2 == ["", "", "", "", "", " "]

Why str1 result that?

2
  • 6
    "str1 == null" no it's not, it's a zero-length array. Commented Mar 11, 2019 at 11:36
  • 4
    From the documentation "Trailing empty strings are therefore not included in the resulting array.". In the first instance every element is a trailing empty string, so the array is empty. In the second instance, there are no trailing empty strings. Commented Mar 11, 2019 at 11:38

2 Answers 2

5

str1 is actually an empty String array, not null.

String[] java.lang.String.split(String regex)

Splits this string around matches of the given regular expression.

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 the result contains only empty strings, they are all removed and the result str1 ends up being an empty array.

That is not the case in the str2 example, where the last string is not empty (it contains a single space) and therefore the (not trailing) empty strings are not removed from the result.

Sign up to request clarification or add additional context in comments.

1 Comment

@AshishkumarSingh The question was about str1 only, but I added an explanation about str2 too.
1

@Eran provided provided the proper explanation. Just to add that if you still want to keep the array with empty Strings, you can use

String[] s_ = str.split("a", 6);
System.out.println("s_ : " + Arrays.toString(s_));

, or any other limit (the number of times the pattern is applied) greater than 6, instead of the simple split.

The latter will print,

s_ : [, , , , , ]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.