5

How can I replace single quote ' with empty string in 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)

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. Please suggest how to go ahead with this?

1
  • Read the doc. data.replace("'", "") would return the new String (not change the current), which is stated in doc: "Returns: The resulting string" Commented Jun 3, 2014 at 12:33

5 Answers 5

7

Use replace, no need for regex.

Remember that Strings are immutable, so you need to assign data.replace("'", ""); to a variable.

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

Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

3

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. But StringBuffer and StringBuilder is mutable in java.

String

StringBuffer

StringBuilder

Comments

2

Just try with:

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

Output:

"foobarbuz"

In your case:

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

Comments

1

Try:

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

OR

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

You would need to assign the replaced string to a variable.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.