2016-12-24 155 views
3

好的,這是我第一次發佈,所以如果我犯了任何錯誤,您將不得不原諒我。長話短說,我給了一個字符串數組,我的目標是保持字符串的唯一字的計數以及從數組中刪除任何標點符號。從字符串中刪除所有非字字符(標點符號)

public static HashMap<String, Integer> uniqueWords(String[] book) { 
    HashMap<String, Integer> hm = new HashMap<>(); 

    for (int i = 0; i < book.length; i++) { 
     if (hm.containsKey(book[i])) { 
      hm.put(book[i], hm.get(book[i]) + 1); 
     } else { 
      book[i] = book[i].replaceAll("[^a-zA-Z]","").replaceAll("\\p{Punct}","").replaceAll("\\W+","").replaceAll("\\n","").toLowerCase(); 
      hm.put(book[i], 1); 
     } 
    } 
    return hm; 
} 

輸入:{ 「紅大馬哈魚」, 「鮭魚」, 「鮭魚」, 「藍魚」, 「鯥」, 「鯥」, 「*」, 「%」, 「」};

輸出:{= 2,青魚= 3,紅魚= 3}

所以我已經設法成功地刪除任何空白,但我仍然有星號亮亮相百分。

任何幫助表示讚賞,謝謝。

回答

0

嘗試這樣的事情 -

public static HashMap<String, Integer> uniqueWords(String[] book) { 
    HashMap<String, Integer> hm = new HashMap<>(); 
string strBook = ""; 
int key = 1; 
    for (int i = 0; i < book.length; i++) { 
    strBook= book[i].replaceAll("[^a-zA-Z]","").replaceAll("\\p{Punct}","").replaceAll("\\W+","").replaceAll("\\n","").toLowerCase(); 
     if (!hm.containsKey(strBook)) { 
      hm.put(key, strBook); 
      key++; 
     } 
    } 
    return hm; 
} 
+0

我想這一些變化都無濟於事,感謝您的解決方案無論哪種方式。 –

+0

我意識到我的錯誤。很少有的情況下,非單詞字符不會附加到包含單詞的字符串,在這種情況下,我的代碼將刪除非單詞字符: –

+0

以下是代碼的最終版本: 公共靜態HashMap uniqueWords(String [] book) { HashMap hm = new HashMap <>();對於(int i = 0; i

相關問題