好的,这是我第一次发帖,如果有任何错误请见谅。简而言之,我得到了一个字符串数组,我的目标是计算字符串中唯一单词的数量,并从数组中删除任何标点符号。
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;
}
输入: {"Redfish", "redfish", "redfish", "Bluefish", "bluefish", "bluefish", "*", "%", ""};
输出: {=2, bluefish=3, redfish=3}
所以我已经成功地去除了任何空格,但仍然计算星号和百分比符号。
如果有帮助,请谢谢。
HashMap hm = new HashMap<>();
for (int i = 0; i < book.length; i++) {
book[i] = removePunctuation(book[i]);
if(!hm.containsKey(book[i]))
hm.put(book[i], 1);
else
hm.put(book[i], hm.get(book[i]) + 1);
}
return hm;
}public static String removePunctuation(String book){ for (int i = 0; i < book.length(); i++) book = book.replaceAll("[^a-zA-Z]", "").toLowerCase();return book;
} - Camilo Riviere