One or more space split strings in JAVA __java

Source: Internet
Author: User
    

The split method of string supports regular expressions;

The regular expression \s to match any white-space character, + to match one or more times. first, the string to be divided

String str = "a  b     c  d E F      g"

Where the white space in the string is: a single space, multiple Spaces, tab tabs. Two, use one or more spaces to split a string

The correct code is as follows:

String [] arr = Str.split ("\\s+");
for (String Ss:arr) {
    System.out.println (ss);
}

As a contrast, the error code is as follows:

String [] arr2 = Str.split ("");
for (String ss:arr2) {
    System.out.println (ss);
}
The test code is as follows:
public class stringmul{
	
     //1. String split public
	 static STRING[]STR1 (string str)
	 {
          System.out.println ("Method one: ");
          String [] arr = Str.split ("");
          return arr;
	 }
	 2. String split public
	 static STRING[]STR2 (string str)
	 {
          System.out.println ("Method two:");
          String [] arr = Str.split ("\\s+");
          return arr;
	 }

	public static void Main (String[]args)
	{ 
		String str = "AB     cdef      g";
	    STRING[]ARR=STR1 (str);
        for (String Ss:arr) {
         System.out.println (ss);
        }
        STRING[]ARR2=STR2 (str);
         for (String ss:arr2) {
         System.out.println (ss);
        }

	}
}

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.