简体   繁体   English

如何在Java中用空字符串替换'

[英]How to replace ' with empty string in Java

How can I replace single quote ' with empty string in Java. 如何在Java中用空字符串替换单引号'。 I tried following but doesn't seem to be working. 我尝试了以下操作,但似乎没有用。

String data="Sid's den";
data.replace("'", "");
data.replaceAll("'", "");

Thanks in advance. 提前致谢。 Any help is much appreciated.(Output should be: Sids den) 非常感谢您的帮助。(输出应为:Sids den)

Thanks guys for your responses. 谢谢你们的回应。 I guess I should have been more clear about my question. 我想我应该对我的问题更清楚了。 Basically I am getting special characters from the table and with what value we have to replace that also from the same table. 基本上,我从表中得到特殊字符,并且从同一个表中我们必须用什么值替换那些特殊字符。 Here is snippet of the code: 这是代码片段:

query = "select spl_char, replace_with from entcon_splchars";
ptsmt = DBConnector.sqlConnection.prepareStatement(query);
rs = ptsmt.executeQuery();

while (rs.next()) {
        if(data.contains(rs.getString("spl_char"))){
          data = data.replace(rs.getString("spl_char"),rs.getString("replace_with"));
            }
         }

so whenevr in the data we have special character ' then I am facing nullpointer exception. 因此,当数据中的evr有特殊字符'时,我将面临nullpointer异常。 Please suggest how to go ahead with this? 请建议如何进行此操作?

Use replace , no need for regex. 使用replace ,不需要正则表达式。

Remember that String s are immutable, so you need to assign data.replace("'", ""); 请记住, String是不可变的,因此您需要分配data.replace("'", ""); to a variable. 到一个变量。

For instance: data = data.replace("'", ""); 例如: data = data.replace("'", "");

Strings are immutable so you'll receive a new instance. 字符串是不可变的,因此您将收到一个新实例。 Try 尝试

 data = data.replace("'", "");

Your Edit 您的编辑

Check the return values of getString() - you could get your NPE because your database table contains null values in one of the columns spl_char or replace_with . 检查getString()的返回值-因为数据库表在spl_charreplace_with列之一中包含null值,所以可以获得NPE

I can see your problem, If you need to replace it you need to replace it and also need to assign it back to the variable. 我可以看到您的问题,如果您需要替换它,则需要替换它,还需要将其分配回该变量。 Solution should be, 解决方法应该是

        String data="Sid's den";

        data = data.replaceAll("'", "");

        System.out.println(data);

Because String is immutable in java. 因为String在Java中是不可变的。 But StringBuffer and StringBuilder is mutable in java. 但是StringBuffer和StringBuilder在Java中是可变的。

String

StringBuffer 字符串缓冲区

StringBuilder StringBuilder

Just try with: 只需尝试:

"foo'bar'buz".replace("'", "")

Output: 输出:

"foobarbuz"

In your case: 在您的情况下:

String data = "Sid's den";
String output = data.replace("'", "");

Try: 尝试:

data = data.replace ("'", "") ;

OR 要么

data = data.replaceAll("'", "") ;

You would need to assign the replaced string to a variable. 您需要将替换后的字符串分配给变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM