java从字符串中删除某些字符
我想创建一个程序,给出字符数,单词数等。。。在用户输入的字符串中。要获得字数,我需要删除字符串中的所有句点和逗号。到目前为止,我有:
import javax.swing.JOptionPane;
public class WordUtilities
{
public static void main(String args[])
{
{
String s = JOptionPane.showInputDialog("Enter in any text.");
int a = s.length();
String str = s.replaceAll(",", "");
String str1 = str.replaceAll(".", "");
System.out.println("Number of characters: " + a);
System.out.println(str1);
}
}
}
但最终我只得到了这个:
Number of characters: (...)
为什么它不给我没有逗号和句点的字符串?我需要修理什么
# 1 楼答案
你可以使用:
而不是:
正如@nachokk所说,您可能想了解一些关于regex的内容,因为
replaceAll
第一个参数需要一个regex表达式编辑:
或者就是这个:
用一句话来表达
# 2 楼答案
你可以用String#replace()代替replaceAll cause String#replaceAll
因此,在代码中使用replace是
或者你可以使用一个合适的正则表达式: