java 这是在java中为字符串附加单引号的最佳方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29516260/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 15:24:15  来源:igfitidea点击:

Which is the best way to append single quotes for a String in java

javastringappendstring-formatting

提问by SHILPA AR

For example,

例如,

String x= "ABC";

Which is the best way to convert ABC to 'ABC' ?

将 ABC 转换为 'ABC' 的最佳方法是什么?

回答by T.Gounelle

This will create less intermediate Stringobjects than with +

这将创建String比使用更少的中间对象+

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'

印刷 'ABC'

回答by Edward Fitzgerald

The other option is the escape character, which in Java is the backslash (). So: String x = "\'ABC\'";

另一个选项是转义字符,在 Java 中是反斜杠 ()。所以:String x = "\'ABC\'";

Here is a good reference.

这是一个很好的参考