2015-11-22 29 views
1

在寫一個從句子中提取單詞的方法的時候,我很困難。這些詞應以aAeEiIoOuU開頭,並且有5個字母,例如乙醚。從句子中提取單詞的方法

該方法應該返回一個字符串數組。我的問題在於,我希望數組的長度與foudn單詞的長度相同。如果它發現3個字,數組長度也應該是3。

這是我的代碼的時刻:

public static String[] extractWords(String text){ 
    String text = "einer hallo hallo einer"; 
    String pattern = "\\b[AaEeIiOoUu]\\p{L}\\p{L}\\p{L}\\p{L}\\b"; 
    Pattern p = Pattern.compile(pattern, Pattern.UNICODE_CASE); 
    Matcher m = p.matcher(text); 

    int i = 0; 
    while (m.find()){ 
     i++; 

    } 

    String[] array = new String[i]; 
    while(m.find()){ 
     System.out.println(m.group()); 
     array[i] = m.group(); 
     i++; 
    } 
} 
+0

爲什麼這會降低投票率? –

+0

你可以發佈你面臨的問題是什麼?它會輸出錯誤嗎?或者是其他東西? –

+0

當找到2個單詞時,數組長度爲3而不是2 – Panikx

回答

0

你應該使用這裏ArrayList。要使用數組,你必須進行兩次匹配,這是不必要的額外工作。

此外,只是你知道,第二個while(m.find())循環,甚至不會運行一次,因爲匹配器已經被第一個循環耗盡。您將需要重新初始化Matcher對象:

Matcher m = p.matcher(text); // Needed before second while loop. 

但是,這是沒有必要的。我們用ArrayList代替:

public static String[] extractWords(String text){ 
    String text = "einer hallo hallo einer"; 
    // Use quantifier to match 4 characters, instead of repeating it 4 times. 
    String pattern = "\\b[AaEeIiOoUu]\\p{L}{4}\\b"; 
    Pattern p = Pattern.compile(pattern, Pattern.UNICODE_CASE); 
    Matcher m = p.matcher(text); 

    List<String> matchedWords = new ArrayList<>(); 

    while (m.find()){ 
     matchedWords.add(m.group()); 
    } 

    // If you want an array, convert the list to array 
    String[] matchedWordArray = matchedWords.toArray(new String[matchedWords.size()]); 
}