The use of the split function in Java for "Small Knowledge Point Summary" _ Block Chain

Source: Internet
Author: User

The Split function in Java is used to segment a string by a specified character (string) or regular, and the result is returned as an array of strings;

For example:

[Java] view plain copy String str= "1234@ABC";   String[] A = Str.split ("@");   SYSTEM.OUT.PRINTLN ("Processing results:" +a[0]+ "," +a[1]); Output is: Processing results: 1234,ABC for the split character (string), is usually common, ordinary, no problem;

However, for certain special characters, if the character (string) is just a part of the regular, you need to escape to use it.

These characters have |, +, *, ^, $,/, |, [,], (,),-,., etc, because they are part of the regular expression, so if you want to use the character itself, these characters need to be escaped to represent itself;

For example:

Want to use | Vertical bar to split a character, because | itself is a part of the regular expression, so you need to escape, because the escape using \, and this \ is also a regular expression of the character, so you have to use a \, so need two \.

[Java] view plain copy String str= "5678|   XYZ ";  String[] B = Str.split ("\\|");   Note that there are two \ n, not one \ System.out.println ("Processing results:" +b[0]+ "," +b[1]); The output is: processing results: 5678,XYZ

Take another look: [Java] view plain copy String str= "5678|   XYZ ";  String[] B = Str.split ("|");   Note Direct Use |, which is part of a regular expression, String x= "processing result:";   for (int i=0;i<b.length;i++) {x=x+b[i]+ ",";   } System.out.println (x); Output is: processing result: 5,6,7,8,|,x,y,z, possibly we artificial subjective feeling is with | To split the hope to get 5678 and XYZ, because with special characters, the actual result is to get unexpected results;

So when you specify a split character (string), it is best not to include the character used for the regular expression itself, such as the red character above;

Related Article

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.