Java Split string

Source: Internet
Author: User

There are two things to keep in mind when using the String.Split function for string segmentation

1. Use \ \ to escape special characters as separators (for example, if you use \ \ As delimiter, then escape to \\\\)

.$| ()[{^?*+\\

For example, the delimiter string is split here

        String str = "A|b|c";         = Str.split ("\\|" );         // output here 3         for (int i = 0; i < strarr.length; + +i) {        System.out.println (strarr[i]); // output a b c        } here

2. Pay attention to the processing of the last empty character (usually there are some cases when the last data is empty, only a delimiter is left, if not processed, the number of data split will deviate from the expected)

        // Notice there's one more at the end | delimiter        string[] Strarr = Str.split ("\\|" );     // output here 3         for (int i = 0; i < strarr.length; + +i) {        System.out.println (strarr[i]); // output a b c        } here

If you need to keep the data for the last empty character, you need to set the second argument of Split to-1

        String str = "a|b|c|"; // Notice there's one more at the end | delimiter        string[] Strarr = Str.split ("\\|",-1); // This sets the second parameter to-1        // output here 4          for (int i = 0; i < strarr.length; + +i) {        System.out.println (strarr[i]); // empty string        }

Above.

Java Split string

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.