2015-03-13 27 views
3

我試圖根據單詞之間的空格拆分輸入句子。它沒有按預期工作。如何使用掃描程序分隔空格作爲分隔符的字符串

public static void main(String[] args) { 
    Scanner scaninput=new Scanner(System.in); 
    String inputSentence = scaninput.next(); 
    String[] result=inputSentence.split("-"); 
    // for(String iter:result) { 
    //  System.out.println("iter:"+iter); 
    // } 
    System.out.println("result.length: "+result.length); 
    for (int count=0;count<result.length;count++) { 
     System.out.println("=="); 
     System.out.println(result[count]); 
    } 
} 

它給下面當我使用輸出「 - 」在分裂:

fsfdsfsd-second-third 
result.length: 3 
== 
fsfdsfsd 
== 
second 
== 
third 

當我替換「 - 」有空間「」,它給下面的輸出。

first second third 
result.length: 1 
== 
first 

有關這裏有什麼問題的任何建議?我已經提到了過帳流程How to split a String by space,但它不起作用。

使用split("\\s+")給出了這樣的輸出:

first second third 
result.length: 1 
== 
first 
+2

如果有多個空格,請嘗試使用'\\ s +'。告訴我們你究竟試過了什麼*完全*。 – TheLostMind 2015-03-13 06:24:32

+0

這是輸出的第一個第二個第三個 result.length:1 == 第一個 – Zack 2015-03-13 06:25:18

+0

在我的問題中添加了相同的更好的視圖。無法在評論中格式化 – Zack 2015-03-13 06:26:38

回答

8

變化

scanner.next() 

scanner.nextLine() 

javadoc

掃描器斷開其輸入爲標記使用DELIM iter模式,它默認匹配空格。

調用next()返回下一
調用nextLine()返回下一個

+0

太棒了!有效。 – Zack 2015-03-13 06:34:48

1

的問題是,scaninput.next()將只讀取,直到第一個空格字符,所以它只能在字first拉動。所以split之後什麼都不做。我建議使用java.io.BufferedReader,這會讓你read an entire line at once

+2

那麼掃描儀沒有錯,他只需要使用'nextLine()'或更改分隔符。 – Obicere 2015-03-13 06:30:00

+0

哪一個更好?掃描儀或緩衝讀取器? – Zack 2015-03-13 06:37:12

7

next()方法Scanner已經將字符串拆分爲空格,也就是說,它返回下一個標記,字符串直到下一個字符串。因此,如果您添加適當的println,您將看到inputSentence等於第一個單詞,而不是整個字符串。

scanInput.next()替換爲scanInput.nextLine()

-1

使用src.split("\\s+");而不是inputSentence.split("-");

它分割上的每個\\s代表每非空白字符。結果是數組如果元素之前,之間和之後的分隔符。

下面是您需要的完整示例。

實施例:

public class StringSplit { 
    public static void main(String[] args) 
    { 
     String src = "first second third"; 
     String[] stringArray = src.split("\\s+"); 

     System.out.println(stringArray[0]); 
     System.out.println(stringArray[1]); 
     System.out.println(stringArray[2]); 
    } 
} 

詳情分裂( 「\ S +」)是如何工作的參考計算器打擊後。

How exactly does String.split() method in Java work when regex is provided?

+0

'\ s'是*空白*,不*非* - 空白 – Bohemian 2015-03-13 11:10:07

0

另一種替代方法是使用緩衝的Reader類,運行良好。

String inputSentence; 

      BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 
      inputSentence=br.readLine(); 

      String[] result=inputSentence.split("\\s+"); 
rintln("result.length: "+result.length); 

      for(int count=0;count<result.length;count++) 
      { 
       System.out.println("=="); 
       System.out.println(result[count]); 
      } 

     } 
相關問題