Reputation: 103
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?
Upvotes: 0
Views: 146
Reputation: 404
@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_ : [, , , , , ]
Upvotes: 1
Reputation: 393771
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.
Upvotes: 5