Java 从字符串中删除某些字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20862001/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 04:52:11  来源:igfitidea点击:

Remove certain characters from string

javastringreplacecharacterreplaceall

提问by f3d0r

I want to create a program that gives the number of characters, words, etc... in a user-inputted string. To get the word count I need to remove all the periods and commas form a string. So far I have this:

我想创建一个程序,在用户输入的字符串中给出字符、单词等的数量。为了获得字数,我需要删除所有的句点和逗号形成一个字符串。到目前为止,我有这个:

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

But in the end I get only this:

但最后我只得到这个:

Number of characters: (...)

Why is it not giving me the string without the commas and periods? What do I need to fix?

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

采纳答案by Christian

You can use:

您可以使用:

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

instead of:

代替:

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

As @nachokk said, you may want to read something about regex, since replaceAllfirst parameter expects for a regex expression.

正如@nachokk 所说,您可能想阅读有关正则表达式的内容,因为replaceAll第一个参数需要正则表达式。

Edit:

编辑:

Or just this:

或者只是这个:

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

to make it all in one sentence.

一言以蔽之。

回答by nachokk

You can just use String#replace()instead of replaceAll cause String#replaceAll

您可以只使用String#replace()而不是 replaceAll 原因String#replaceAll

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

用给定的替换替换此字符串中与给定正则表达式匹配的每个子字符串。

So in code with replace is

所以在代码中替换是

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

Or you could use a proper regular expression all in one:

或者,您可以合二为一地使用适当的正则表达式:

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