'Which is the best way to append single quotes for a String in java
For example,
String x= "ABC";
Which is the best way to convert ABC to 'ABC' ?
Solution 1:[1]
You can use String
inner StringBuilder
like
sb.append(String.format("'%s'", variable));
Solution 2:[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:[3]
The other option is the escape character, which in Java is the backslash ().
So: String x = "\'ABC\'";
Here is a good reference.
Solution 4:[4]
For those who uses Spring Framework:
import org.springframework.util.StringUtils;
String x = "ABC";
x = StringUtils.quote(x);
Quote the given String with single quotes.
Parameters:
str - the input String (e.g. "myString")
Returns:
the quoted String (e.g. "'myString'"), or null if the input was null
Consider also StringUtils.quoteIfString(Object obj)
.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Suraj Rao |
Solution 2 | T.Gounelle |
Solution 3 | Edward Fitzgerald |
Solution 4 | Woland |