Confusion with line splitting method

I looked at the documentation on line splitting, but the results are not as expected. When we split a string with a limit argument set to a negative value, it always adds an empty value. Why do this? Consider some cases

// Case 1
String str = "1#2#3#";
System.out.println(str.split("#").length); // Prints 3
System.out.println(str.split("#", -1).length); // Prints 4

What I expect here is like 3 fingerprints.

// Case 2
str = "";
System.out.println(str.split("#").length); // Prints 1
System.out.println(str.split("#", -1).length); // Prints 1

Now, since no match was found, the normal split method without restrictions should print 0, but it creates an array with an empty string.

// Case 3
str = "#";
System.out.println(str.split("#").length); // Prints 0
System.out.println(str.split("#", -1).length); // Prints 2

Now I have a match and the split method works without a limit argument. This is my expected result, but why not create an empty array in this case, as in case 2?

// Case 4
str = "###";
System.out.println(str.split("#").length); // Prints 0
System.out.println(str.split("#", -1).length); // Prints 4

Here the first separation method is as expected, but why does the second give 4 instead of 3?

// Case 5
str = "1#2#3#";
System.out.println(str.split("#", 0).length); // Prints 3
System.out.println(str.split("#", 3).length); // Prints 3
System.out.println(str.split("#", 4).length); // Prints 4

. <= , , . , .

+4
3

JavaDoc String

, , , . n , n - 1 , n . n , , . n , , , .

.

, , E:

1#2#3# -> 1 # 2 # 3 # E
E      -> E
#      -> E # E
###    -> E # E # E # E

( ) , n == 0.

+6

:

... n - , ... .

, .

+3

, , . n , n - 1 , n, . n , , , . n , , , , .

, limit - .

+2

Source: https://habr.com/ru/post/1548093/


All Articles