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
.
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.
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.
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.
Use str.Call str. replace(old, new) with old as "'" and new as "" to remove all single quotes from the string.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With