有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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: (...)

为什么它不给我没有逗号和句点的字符串?我需要修理什么


共 (2) 个答案

  1. # 1 楼答案

    你可以使用:

    String str1 = str.replaceAll("[.]", "");
    

    而不是:

    String str1 = str.replaceAll(".", "");
    

    正如@nachokk所说,您可能想了解一些关于regex的内容,因为replaceAll第一个参数需要一个regex表达式

    编辑:

    或者就是这个:

    String str1 = s.replaceAll("[,.]", "");
    

    用一句话来表达

  2. # 2 楼答案

    你可以用String#replace()代替replaceAll cause String#replaceAll

    Replaces each substring of this string that matches the given regular expression with the given replacement.

    因此,在代码中使用replace是

     str = str.replace(",","");
     str = str.replace(".","");
    

    或者你可以使用一个合适的正则表达式:

    str = str.replaceAll("[.,]", "");