"\\s+"的使用


詳解 "\\s+"

正則表達式中\s匹配任何空白字符,包括空格、制表符、換頁符等等, 等價於[ \f\n\r\t\v]

  • \f -> 匹配一個換頁
  • \n -> 匹配一個換行符
  • \r -> 匹配一個回車符
  • \t -> 匹配一個制表符
  • \v -> 匹配一個垂直制表符

而“\s+”則表示匹配任意多個上面的字符。另因為反斜杠在Java里是轉義字符,所以在Java里,我們要這么用“\\s+”.

那么問題來了,“\\s+”有啥使用場景呢?

舉例——排序

假設一個輸入場景:用冒泡排序算法對一組數字進行從小到大排序

輸入:輸入的是一行數字,就是我們需要排序的數字

輸出:輸出是從小到大排序好的數字,數字之間用空格分開

樣例輸入

2 1 5 8 21 12

樣例輸出

1 2 5 8 12 21
方法1:
import java.util.Scanner;
public class test{
    public static void main(String[] args) {  
        Scanner sc = new Scanner(System.in);  
        String s = sc.nextLine();//將用戶輸入的一整行字符串賦給s  
        String[] c = s.split(" ");//用空格將其分割成字符串數組  
        
        int size = c.length;  
        int[] b =new int[size];  
        for (int m = 0; m < b.length; m++) {  
            b[m] = Integer.parseInt(c[m]);//講字符串數組轉換成int數組  
        }  
        int temp=0;  
        for (int i = 0; i < b.length; i++) {  
            for (int j = 0; j < b.length-i-1; j++) {  
                if(b[j]>b[j+1]){  
                    temp=b[j];  
                    b[j]=b[j+1];  
                    b[j+1]=temp;  
                }  
            }  
        }  
          
        for(int n = 0; n < b.length ; n++){  
            System.out.print(b[n]);  
            System.out.print(' ');  
        }  
            sc.close();   
    }
}

方法2:

import java.util.Scanner;
public class test{
    public static void main(String[] args) {  
        Scanner sc = new Scanner(System.in);  
        String s = sc.nextLine();//將用戶輸入的一整行字符串賦給s  
        String[] c = s.split("\\s+");//用空格將其分割成字符串數組  
        
        int size = c.length;  
        int[] b =new int[size];  
        for (int m = 0; m < b.length; m++) {  
            b[m] = Integer.parseInt(c[m]);//講字符串數組轉換成int數組  
        }  
        int temp=0;  
        for (int i = 0; i < b.length; i++) {  
            for (int j = 0; j < b.length-i-1; j++) {  
                if(b[j]>b[j+1]){  
                    temp=b[j];  
                    b[j]=b[j+1];  
                    b[j+1]=temp;  
                }  
            }  
        }  
          
        for(int n = 0; n < b.length ; n++){  
            System.out.print(b[n]);  
            System.out.print(' ');  
        }  
            sc.close();   
    }
}

這兩個方法的區別就是

用它:String[] c = s.split(" ");還是用它:String[] c = s.split("\\s+");
假如我們輸入的是:1 2 3   12  11這樣的數據,換言之就是數字之間有多個空格的時候,方法1將會報錯,而方法2正常排序運行。因為方法1只能匹配一個空格,而方法2可以匹配多個空格。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM