java Split 實現去除一個空格和多個空格
用Split函數可以去除輸入一個字符串中的空格,并且一般都是將它存儲在一個字符串數組之中
例如:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); String s=in.nextLine(); //如果我輸入:0 1 2 3 4 String[] str=s.split(' '); System.out.println(s); System.out.println(str[3]); } }
輸出結果是:
0 1 2 3 4
3
可是會出現這種情況,如果我輸入的是0 1 2 3 4,在2和3之間有3個的空格,那還會有用嗎?
結果輸出是:
0 1 2 (空格) 3 4
(空格)
也就是沒有輸出str[3],至少看上去是這樣的,然后我分析得出結論,其實是這樣的,
舉個例子,我輸入2(空)(空)(空)3,執行Split函數后得到的String str數組
是str[0]=2 ,str[1]=(空),str[2]=(空),str[3]=3
也就是說,Split函數在執行多空格判斷時,會只將第一個空格忽略,其余空格都放入數組,直到遇到非空格數3,然后后面的情況重復,只有一個空格,情況是結果是理想的,多個空格,又是重復如此
解決方法:
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+ '); //改動這里 System.out.println(s); System.out.println(str[3]); } }
利用正則表達式,就可以實現我們理想的結果,
例如:輸入2(空)(空)(空)3
結果:
str[0]=2
str[1]=3
補充知識:Java 鍵盤輸入數字(空格隔開) 將數字存入數組
Scanner方法
核心是單行輸入字符串,切割字符串中的空格,存入數組
Scanner s = new Scanner(System.in);String inputStr = s.nextLine();String[] strArray = inputStr.split(' ');int[] num = new int[strArray.length];for(int i = 0 ; i < num.length ; i++){ num[i] = Integer.parseInt(strArray[i]);}
Scanner輸入的一個問題:在Scanner類中如果我們在任何7個nextXXX()方法之后調用nextLine()方法,這nextLine()方法不能夠從控制臺讀取任何內容,并且,這游標不會進入控制臺,它將跳過這一步。nextXXX()方法包括nextInt(),nextFloat(), nextByte(),nextShort(),nextDouble(),nextLong(),next()。此時應該使用BufferedReader。 ?
BufferedReader方法
首行輸入數組大小,次行輸入數組內容,依次用空格隔開。
它的優勢在于消耗比scanner更少的內存和時間,如果在寫算法時優先使用BufferedReader方法。
注意:使用完記得close,Scanner方法不需要close。
public static int[] ListInput() throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int N = 0; String str = null; N= Integer.parseInt(br.readLine()); str = br.readLine(); br.close(); int[] myList = new int[N]; String[] strArray = str.split(' '); for (int i = 0; i < N; i++) { myList[i] = Integer.parseInt(strArray[i]); } return myList;}···
以上這篇java Split 實現去除一個空格和多個空格就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網。
相關文章: