如何在Java中用空格替换双引号?

2022-09-01 15:22:45

例如:

"I don't like these "double" quotes"

我希望输出是

I don't like these double quotes

答案 1

使用 String#replace()

要将它们替换为空格(根据您的问题标题):

System.out.println("I don't like these \"double\" quotes".replace("\"", " "));

上述操作也可以用字符完成:

System.out.println("I don't like these \"double\" quotes".replace('"', ' '));

要删除它们(根据您的示例):

System.out.println("I don't like these \"double\" quotes".replace("\"", ""));

答案 2

您不需要正则表达式。只需逐个字符替换就足够了。您可以使用 String#replace() 来实现此目的。

String replaced = original.replace("\"", " ");

请注意,您也可以使用空字符串代替替换。否则,空间会加倍。""

String replaced = original.replace("\"", "");