【问题标题】:Removing All Non-Word Characters (Punctuation) From A String从字符串中删除所有非单词字符(标点符号)
【发布时间】: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


    【解决方案1】:

    试试这样的——

        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;
    }
    

    【讨论】:

    • 我尝试了一些变体无济于事,无论哪种方式都感谢您的解决方案。
    • 我意识到我的错误。很少会出现非单词字符不会附加到包含单词的字符串的情况,在这种情况下,我的代码将删除非单词字符:
    • 这是代码的最终版本: public static HashMap uniqueWords(String[] book) { HashMap hm = new HashMap(); for (int i = 0; i
    • 很好,很高兴你解决了这个问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-25
    • 1970-01-01
    • 1970-01-01
    • 2010-12-09
    • 2011-08-16
    相关资源
    最近更新 更多