【发布时间】:2017-05-09 14:55:26
【问题描述】:
好的,这是我第一次发帖,如有错误请见谅。长话短说,我得到了一个字符串数组,我的目标是计算字符串中唯一单词的数量,并从数组中删除任何标点符号。
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}
所以我已经成功地删除了所有空白,但我仍然有星号和百分位数正在计算中。
感谢您的帮助,谢谢。
【问题讨论】:
标签: java string special-characters removing-whitespace