Java split how to remove a space and multiple spaces

Source: Internet
Author: User

You can use the Split function to get rid of spaces in a string and generally store it in a string array

For example:

Import Java.util.Scanner;  
  
public class Main {public  
  
  
    static void Main (string[] args) {  
        Scanner in = new Scanner (system.in);  
        String s=in.nextline ();   If I enter: 0 1 2 3 4
        string[] Str=s.split ("");
        System.out.println (s);
        System.out.println (Str[3]);
        
    }  
  

The output results are:

0 1 2 3 4

3


However, if I enter 0 1 2 3 4, there are 2 spaces between 3 and 3, would that still be useful.

The resulting output is:

0 1 2 (space) 3 4

Spaces

That is, there is no output STR[3], at least it looks like this, and then I came to the conclusion that, actually,

For example, I enter 2 (empty) (empty) 3, the string str array that is executed after the split function.

Is str[0]=2, str[1]= (empty), str[2]= (empty), str[3]=3

In other words, the split function in the execution of multiple space to judge, will only ignore the first space, the remaining spaces are placed in the array, until the number of spaces 3, and then repeat the situation, only a space, the situation is the result is ideal, multiple spaces, but also repeat so


Workaround:

Import Java.util.Scanner;  
  
public class Main {public  
  
  
    static void Main (string[] args) {  
        Scanner in = new Scanner (system.in);  
        String s=in.nextline ();
        String[] Str=s.split ("\\s+");   Change here
        System.out.println (s);
        System.out.println (Str[3]);
        
    }  
  

Using regular expressions, we can achieve our desired results,

For example: Enter 2 (empty) (empty) (empty) 3

Result: str[0]=2

Str[1]=3





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.