2012-05-25 45 views
0

我有一個文件,該文件的格式如下:數字符的特定字符之間的數(包括空格)

City|the Location|the residence of the customer| the age of the customer| the first name of the customer| 

我需要閱讀只是第一線的確定有多少個字符符號之間「|」。我需要代碼來讀取空間。

這是我的代碼:

`FileInputStream fs = new FileInputStream("C:/test.txt"); 
BufferedReader br = new BufferedReader(new InputStreamReader(fs)); 
StringBuilder sb = new StringBuilder(); 

for(int i = 0; i < 0; i++){ 
br.readLine(); 
} 
String line = br.readLine(); 

System.out.println(line); 

String[] words = line.split("|"); 
for (int i = 0; i < words.length; i++) { 
    int counter = 0; 
    if (words[i].length() >= 1) { 
     for (int k = 0; k < words[i].length(); k++) { 
      if (Character.isLetter(words[i].charAt(k))) 
       counter++; 
     } 
     sb = new StringBuffer(); 
     sb.append(counter).append(" "); 
    } 
} 
System.out.println(sb); 
} 

`

我很新的Java

+0

然後你可以將單詞轉換爲字符數組,然後獲取長度? –

回答

2

嘗試這樣:

String line = "City|the Location|the residence of the customer| the age of the customer| the first name of the customer|"; 
String[] split = line.split("\\|"); //Note you need the \\ as an escape for the regex Match 
for (int i = 0; i < split.length; i++) { 
    System.out.println("length of " + i + " is " + split[i].length()); 
} 

輸出:

length of 0 is 4 
length of 1 is 12 
length of 2 is 29 
length of 3 is 24 
length of 4 is 31 
3

我需要閱讀只是第一線的確定有多少個字符在符號「|」之間。我需要代碼來讀取空間。

String.split採用正則表達式,所以需要|轉義。使用\\|然後

words[i].length() 

會給你|符號之間的字符數。

2

第一:

for(int i = 0; i < 0; i++){ 
    br.readLine(); 
} 

,因爲你進入for只有i不如這將做什麼0

然後:

if (words[i].length() >= 1) { 

if不是很有用,因爲你不會進入下一個for如果words[i].length()是0

最後沒有測試它,它似乎是相當正確的,你可能要測試是否字符是字母ORwords[i].charAt(k).equals(" ")的空間

1

爲了更好performaces而不是使用String.split(),這裏一個例子的StringTokenizer:

FileInputStream fs = new FileInputStream("C:/test.txt"); 
BufferedReader br = new BufferedReader(new InputStreamReader(fs)); 
StringBuilder sb = new StringBuilder(); 

String line = br.readLine(); 

System.out.println(line); 

StringTokenizer tokenizer = new StringTokenizer(line, "|"); 
while (tokenizer.hasMoreTokens()) { 
    String token = tokenizer.nextToken(); 
    sb.append(token.length()).append(" "); 
} 
System.out.println(sb.toString()); 
相關問題