Scanner 類 useDelimiter("")用法--轉載

            Scanner類從字面上講是“掃描”的意思,它把給定的字符串解析成Java的各種基本數據類型primitive types,用於分解字符串的默認的分隔符是空格,當然也可以定製。

例如:Scanner sc = new Scanner(System.in);其構造函數參數是待解析的輸入源,可以是File對象、Stream對象,或是一個String,然後還有java.lang.Readable對象。

定製分隔符的方法是sc. useDelimiterj(Pattern),然後使用while循環和sc.next()來依次取出Scanner解析後的元素,還可以特定取sc.nextInt()/ nextLong()/ nextShort()/ nextDouble()等等。

最後,不管輸入源是不是Stream,都請執行sc.close()方法,關閉Scanner,它同時會關閉其輸入源(the source implements the Closeable interface)

       import java.io.*;

       import java.util.*;

       public class ScanFar {

       public static void main(String[] args) throws IOException {

        Scanner sc =

                new Scanner(new BufferedReader(new FileReader("words.txt")));

      //  sc.useDelimiter("分隔符"); 默認是空格

        while (sc.hasNext()) {

            System.out.println(sc.next());

        }

         sc.close();

       }

     }

   如果words.txt文件中的內容是:“So she went into the garden... 那麼結果如下,整個字符串按空格來分爲了多個String對象

       So

       she

       went

       into

       the

       garden...

       如果sc.useDelimiter("t"),那麼結果按字母t來分解,如下:

       So she wen 

       in

       o

       he  garden... 發現被定義爲分隔符的字母t被消除了,不作爲結果的一部分。 

      以前常常遇到要從字符串中取出某些部分,有了Scanner類,比Split()方便靈活多了。

注:sc.next()是從結果集中連續取值,如果要從一串字符中取出間插在中間的數字,那麼使用sc.nextInt(),但是如果結果集中的下一個元素不是int類型的話就會拋出異常,要達到這一目的,在循環中添加if條件判斷即可,如下:

While(sc.hasNext()){

if(sc.hasNextInt()){ // sc.hasNextShort()/hasNextDouble/…等各種基本數據類型

//做事件

}

else{

next();//直接跳過

}

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章