2012-12-29 35 views
2

我與UVa #494玩分裂的話,我設法與下面的代碼來解決這個問題:弗吉尼亞#494 - 正則表達式[^ A-ZA-Z] +使用Java

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStreamReader; 

class Main {  
    public static void main(String[] args) throws IOException{ 
     BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); 
     String line; 
     while((line = in.readLine()) != null){ 
      String words[] = line.split("[^a-zA-z]+"); 
      int cnt = words.length; 
      // for some reason it is counting two words for 234234ddfdfd and words[0] is empty 
      if(cnt != 0 && words[0].isEmpty()) cnt--; // ugly fix, if has words and the first is empty, reduce one word 
      System.out.println(cnt); 
     } 
     System.exit(0); 
    } 
} 

我建的正則表達式"[^a-zA-z]+"分詞,例如字符串abc..abcabc432abc應該拆分爲["abc", "abc"]。但是,當我嘗試使用字符串432abc時,我的結果是["", "abc"] - words[]中的第一個元素只是一個空字符串,但我期望只有["abc"]。我無法弄清楚爲什麼這個正則表達式給了我第一個元素""這種情況。

回答

8

檢查分割參考頁:split reference

分離器中的每個元素定義了單獨的分隔符。如果 兩個分隔符相鄰,或者在開頭 或此實例的結尾處找到分隔符,則相應的數組元素包含 爲空。下表提供了示例。

既然你有幾個連續的分隔符,你會得到空數組元素

3

打印字數的計數

public static void main(String[] args) throws IOException { 
     BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); 
     String line; 
     while ((line = in.readLine()) != null) { 
      Pattern pattern = Pattern.compile("[a-zA-z]+"); 
      Matcher matcher = pattern.matcher(line); 
      int count = 0; 
      while (matcher.find()) { 
       count++; 
       System.out.println(matcher.group()); 
      } 
      System.out.println(count); 
     } 
    }