Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Single quotes replace in Java

Tags:

java

In Java I have:

String str = "Welcome 'thanks' How are you?";

I need to replace the single quotes in str by \', that is, when I print str I should get output as Welcome \'thanks\' How are you.

like image 389
dpaksp Avatar asked Jul 01 '10 08:07

dpaksp


People also ask

How do you replace a single quote in Java?

This uses String. replace(CharSequence, CharSequence) method to do string replacement. Remember that \ is an escape character for Java string literals; that is, "\\'" contains 2 characters, a backslash and a single quote.

How do you replace a single quote?

Use the String. replace() method to replace single with double quotes, e.g. const replaced = str. replace(/'/g, " ); . The replace method will return a new string where all occurrences of single quotes are replaced with double quotes.

How do you handle a single quote in a string in Java?

Core Java bootcamp program with Hands on practice Above, for single quote, we have to mention it normally like. However, for double quotes, use the following and add a slash in the beginning as well as at the end. String str2 = "\"This is it\"!"; The following is an example.

How do you remove single quotes from a string?

Use str.Call str. replace(old, new) with old as "'" and new as "" to remove all single quotes from the string.


1 Answers

It looks like perhaps you want something like this:

    String s = "Hello 'thanks' bye";
    s = s.replace("'", "\\'");
    System.out.println(s);
    // Hello \'thanks\' bye

This uses String.replace(CharSequence, CharSequence) method to do string replacement. Remember that \ is an escape character for Java string literals; that is, "\\'" contains 2 characters, a backslash and a single quote.

References

  • JLS 3.10.6 Escape Sequences for Character and String Literals
like image 171
polygenelubricants Avatar answered Oct 01 '22 13:10

polygenelubricants