有没有办法避免这种重复的方法调用?

Is there a way to avoid this repetitive method calling?

我正在使用 HashMap 来计算一篇文章中的所有单词实例,我试图删除除空格之外的所有非单词字符(因为它们已被 .split() 删除)。有没有一种方法可以不每次都重复 "pWord = pWord.replace(...);" 而是循环并在括号内传递不同的参数?

pWord = pWord.replace('"', '\"');
pWord = pWord.replace("–", "");
pWord = pWord.replace("\"", "");
pWord = pWord.replace(".", "");
pWord = pWord.replace("-", "");

如果要删除 所有非字母 字符,另一种方法是重写字符串,忽略所有其他符号。

String s = "hello world _!@#";
StringBuilder sb = new StringBuilder();
for (char c : s.toCharArray()) {
    if (Character.isDigit(c) || Character.isLetter(c) || Character.isWhitespace(c))
        sb.append(c);
}
s = sb.toString();
System.out.println(s);

实现此目的的一种方法是将 replaceAll 与正则表达式结合使用。以下是您要在代码中替换的字符的正则表达式示例代码:

String pWord = "-asdf\\adf.asdf\"";
System.out.println(pWord.replaceAll("[(\")(\\).-]", ""));

输出:

asdfadfasdf

另外,注意 that

The String#replaceAll() interprets the argument as a regular expression. The \ is an escape character in both String and regex. You need to double-escape it for regex

P.S。测试正则表达式的有用资源:https://regex101.com/