用字符串中的另一个字符替换“字符”

问题描述 投票:-3回答:8

我如何将双引号替换为单引号,例如:我想要有“根本没有被替换的地方。我试过了

String quoteid3 = quoteid2.replace('"','');

它会导致错误。

java
8个回答
0
投票

要替换“,请将双引号转义为\”。使用replaceAll()提供一个可识别所有'和'的正则表达式[\“\'],并用字符串中的”“替换它以删除值(不用替换它们)。

String quoteid3 = quoteid2.replaceAll("[\"\']", "");

//To replace() without regex:-
String quoteid3 =quoteid2.replace("\"","").replace("\'","");

1
投票

你需要逃避你的报价。像这样,可能会有所帮助:

String quoteid3 = quoteid2.replace('\"','\'');

0
投票

这应该工作:

String quoteid3 = quoteid2.replaceAll("\"", ""); 

0
投票

有两个版本的String.replace,一个采用一对char值,另一个采用一对String值。如果您希望替换值为空,则需要使用字符串版本,即使用双引号(而不是单引号)。

String quoteid3 = quoteid2.replace("\"","");

在Java中,单个引用的文字是char,因此必须恰好是一个字符 - ''无效。双引号文字表示字符串,因此可以是从零开始的任意数量的字符。


0
投票

为了取代",逃脱双引号\",同样逃脱'\'

使用replaceAll()提供一个正则表达式[\"\'],它识别所有'",并用字符串中的""替换它以删除值(替换它们没有任何东西)。

String quoteid3 = quoteid2.replaceAll("[\"\']", "");

或者如果你想坚持使用没有正则表达式的replace(): -

String quoteid3 =quoteid2.replace("\"","").replace("\'","");

0
投票

如果你想替换“,逃避双引号”,同样逃避'与'

使用replaceAll()提供一个可识别所有'和'的正则表达式[\“\'],并用字符串中的”“替换它以删除值(不用替换它们)。

String quoteid3 = quoteid2.replaceAll("[\"\']", "");

或者,如果你想坚持使用不带正则表达式的replace(): -

String quoteid3 =quoteid2.replace("\"","").replace("\'","");

0
投票

如果你想替换“,逃避双引号”,同样逃避'与'

使用replaceAll()提供一个可识别所有'和'的正则表达式[\“\'],并用字符串中的”“替换它以删除值(不用替换它们)。

String quoteid3 = quoteid2.replaceAll("[\"\']", "");

或者,如果你想坚持使用不带正则表达式的replace(): -

String quoteid3 =quoteid2.replace("\"","").replace("\'","");

0
投票

空字符串是char[]上的包装器,没有元素。你可以有一个空的char[]。但你不能有一个“空”的字符。与其他原语一样,char必须具有值。

因此,如果您想要将所有Double引号替换为单引号,则可以尝试以下内容:

String str1="Hossam Hassan \"Greeting you\" \'  \' \'";
System.out.println(str1);
String str2=str1.replaceAll("\"", "");
str2=str2.replaceAll("\'", "");
System.out.println(str2);

结果应该是:

Hossam Hassan "Greeting you" '  ' '
Hossam Hassan Greeting you    
© www.soinside.com 2019 - 2024. All rights reserved.