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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2360231/
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 06:32:37  来源:igfitidea点击:

How do you replace double quotes with a blank space in Java?

javareplacequotesregex

提问by angad Soni

For example:

例如:

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

and I want the output to be

我希望输出是

I don't like these double quotes

采纳答案by cletus

Use String#replace().

使用String#replace().

To replace them with spaces (as per your question title):

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

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

The above can also be done with characters:

以上也可以用字符来完成:

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

To remove them (as per your example):

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

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

回答by Mike Trpcic

You can do it like this:

你可以这样做:

string tmp = "Hello 'World'";
tmp.replace("'", "");

But that will just replace single quotes. To replace double quotes, you must first escape them, like so:

但这只会替换单引号。要替换双引号,您必须首先对它们进行转义,如下所示:

string tmp = "Hello, \"World\"";
tmp.replace("\"", "");

You can replace it with a space, or just leave it empty (I believe you wanted it to be left blank, but your question title implies otherwise.

您可以用空格替换它,也可以将其留空(我相信您希望将其留空,但您的问题标题暗示了其他情况。

回答by BalusC

You don't need regex for this. Just a character-by-character replace is sufficient. You can use String#replace()for this.

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

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

Note that you can also use an empty string ""instead to replace with. Else the spaces would double up.

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

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

回答by IanW

Strings are immutable, so you need to say

字符串是不可变的,所以你需要说

sInputString = sInputString("\"","");

not just the right side of the =

不只是右侧=