2014-04-12 56 views
1

我正在處理的數據是一個字符串,後跟空格,然後是數字值。Java使用整數的字母和數字解析Sting

ncols   10812 
nrows   10812 
xllcorner  -107.0005555556 
yllcorner  36.99944444444 
cellsize  9.2592592593e-05 

我想只讀取數值。我知道從字符串到整數或雙精度我可以使用標準類型轉換。

Integer.valueOf(stringOfInteger); 
Double.valueOf(stringOfDouble); 

爲了得到公正的數值我想這是一個測試:

BufferedReader br = new BufferedReader(new FileReader(path)); 
String line = br.readLine(); 
line.replace("[a-z]",""); 
line.replace(" ",""); 
System.out.println(line); 

,並輸出ncols 10812

我也擔心讀取單元大小的值,因爲它有一個指數。

+2

(1)'replace'不使用正則表達式,'replaceAll'。 (2)字符串是不可變的,'replace'的結果不影響原始字符串,但返回新的替換內容 – Pshemo

回答

2

您可以爲每個行做到這一點:

... 
String[] fields = line.split("\\s+"); 
String name = fields[0]; 
float value = Float.parseFloat(fields[1]); 
... 

此代碼將拆分使用空格作爲分隔符場的每行。第一個字段是String,因此您可以直接使用它(或忽略它)。第二個是Float的值,所以你必須在使用它之前將其轉換。如果您願意,可以使用Double

+0

謝謝!很棒。其中一天,我應該坐下來學習正則表達式。 – voltnor

+0

不客氣!正則表達式改變我的生活:) –

0

試試這個

BufferedReader br = new BufferedReader(new FileReader(path)); 
    String line = null; 
    while ((line = br.readLine()) != null) { 
     // split each line based on spaces 
     String[] words = line.split("\\s+"); 
     //first word is name 
     String name = words[0]; 
     // next word is actual number 
     Double value = Double.valueOf(words[1]); 
     System.out.println(name + ":" + value); 
    } 
    // don't forget to close the stream 
    br.close(); 

輸出:

ncols:10812.0 
    nrows:10812.0 
    xllcorner:-107.0005555556 
    yllcorner:36.99944444444 
    cellsize:9.2592592593E-5 
0

如果你想要的所有的數值做對空間和第二項將包含數值的分裂。然後,您可以根據需要進行任何轉化,無需擔心刪除任何指數。

String[] data = new line.split(" "); 
//remove all the spaces from the second array for your data 
data[1] = data[1].replaceAll("\\s", ""); 
//parse to whatever you need data[1] to be 
0

您可以使用split功能Java如下:

String [] dataArr = data.split("[ \t]+"); //assumes @data is you data string variable name 

dataArr的話,會是這樣的:

dataArr[0] = "ncols" 
dataArr[1] = "10812" 
dataArr[2] = "nrows" 
dataArr[3] = "10812" 
. 
. 
. 

dataArr[n - 1] = "9.2592592593e-05" // @n is the size of the array 

你可以的話,使用Integer.parseInt(String str)將您的數字數據解析爲整數。