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可以匹配多个空格。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。