My colleague raised a question to the author today about string splitting. I believe that many new beginners may even be surprised when they have been working for several years. If you are not talking nonsense, simply go to the instance code...
String source = "1,2,,3,";String[] strArr = source.split(",");for (String str : strArr) { System.out.println("[" + str + "]");}
Run the above Code and get the following output on the console:
[1][2][][3]
Now, I just want to ask James Gosling where is my last empty string?
On the jdk api, there is a description of the split method: The method calls split (RegEx, 0), and the description of Split (RegEx, limit) is: the array returned by this method contains each substring of the string, which is terminated by another specified character expression or the end of the string. The order of substrings in the array is the order in which they appear in the string. If the expression does not match any part of the input string, the result array has only one element and this string. The number of times the limit parameter control mode is applied, thus affecting the length of the result array. If the limit value is greater than 0, the mode will be applied limit-1 times at most. The length of the array will not be greater than the limit value. The last entry of the array will contain the part that the input does not match. If limit is not a positive number, the pattern will be applied multiple times as much as possible, and the array will be of any length. If the limit value is 0, trailing empty strings are discarded. Therefore, if you want to keep trailing empty strings, the second parameter should be a negative number.
Modify the previous code:
String source = "1,2,,3,";String[] strArr = source.split(",", -1);for (String str : strArr) { System.out.println("[" + str + "]");}
Run again and get the following results:
[1][2][][3][]
Some Opinions on the string split method