Some Opinions on the string split method

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.