[英]Removing All Non-Word Characters (Punctuation) From A String
好的,這是我第一次發帖,所以如果我犯了任何錯誤,你不得不原諒我。 總而言之,我給了一個字符串數組,我的目標是保持字符串的唯一字數,並從數組中刪除任何標點字符。
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,藍魚= 3,紅魚= 3}
所以我設法成功刪除了任何空格,但我仍然有星號和百分位數。
感謝任何幫助,謝謝。
嘗試這樣的事情 -
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.