Which is the best way to append single quotes for a String in java
27,464
Solution 1
You can use String
inner StringBuilder
like
sb.append(String.format("'%s'", variable));
Solution 2
This will create less intermediate String
objects than with +
public static String quote(String s) {
return new StringBuilder()
.append('\'')
.append(s)
.append('\'')
.toString();
}
public static void main(String[] args) {
String x = "ABC";
String quotedX = quote(x);
System.out.println(quotedX);
}
prints 'ABC'
Solution 3
The other option is the escape character, which in Java is the backslash ().
So: String x = "\'ABC\'";
Here is a good reference.
Author by
SHILPA AR
I am a developer with around 4 years of experience. Curious at times and lost at times. Both the times, this site does help.
Updated on July 09, 2022Comments
-
SHILPA AR almost 2 years
For example,
String x= "ABC";
Which is the best way to convert ABC to 'ABC' ?