Java:StringBuffer 和串联

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/152190/
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-08-11 08:58:11  来源:igfitidea点击:

Java: StringBuffer & Concatenation

javaconcatenationstringbuffer

提问by Jean Paul Galea

I'm using StringBuffer in Java to concat strings together, like so:

我在 Java 中使用 StringBuffer 将字符串连接在一起,如下所示:

StringBuffer str = new StringBuffer();

str.append("string value");

I would like to know if there's a method (although I didn't find anything from a quick glance at the documentation) or some other way to add "padding".

我想知道是否有一种方法(尽管我通过快速浏览文档没有找到任何东西)或其他添加“填充”的方法。

Let me explain; every time I append something to the string, I want to add a space in the end, like so:

让我解释; 每次我向字符串附加一些内容时,我都想在最后添加一个空格,如下所示:

String foo = "string value";
str.append(foo + " ");

and I have several calls to append.. and every time, I want to add a space. Is there a way to set the object so that it will add a space automatically after each append?

我有几个电话要追加.. 每次,我都想添加一个空格。有没有办法设置对象,以便在每次追加后自动添加一个空格?

EDIT --

编辑 -

String input
StringBuffer query = new StringBuffer();
Scanner scanner = new Scanner(System.in);
scanner.UseDelimiter("\n");

do {
   System.out.println("sql> ");

   input = scanner.next();

   if (!empty(input)) query.append(input);

   if (query.toString().trim().endsWith(";")) {
         //run query
   }
}
while (!input.equalsIgnoreCase("exit");

I'll use StringBuilder though as grom suggested, but that's how the code looks right now

我会按照 grom 的建议使用 StringBuilder,但这就是代码现在的样子

采纳答案by kolrie

I think this is handled easier either with a helper method (untested code):

我认为使用辅助方法(未经测试的代码)可以更轻松地处理此问题:

public String myMethod() {
    StringBuilder sb = new StringBuilder();
    addToBuffer(sb, "Hello").addToBuffer("there,");
    addToBuffer(sb, "it").addToBuffer(sb, "works");
}

private StringBuilder addToBuffer(StringBuilder sb, String what) {
    return sb.append(what).append(' ');  // char is even faster here! ;)
}

Or even using a Builder pattern with a fluent interface (also untested code):

或者甚至使用具有流畅界面的 Builder 模式(也是未经测试的代码):

public String myMethod() {
    SBBuilder builder = new SBBuilder()
        .add("Hello").add("there")
        .add("it", "works", "just", "fine!");

    for (int i = 0; i < 10; i++) {
        builder.add("adding").add(String.valueOf(i));
    }

    System.out.println(builder.build());
}

public static class SBBuilder {
    private StringBuilder sb = new StringBuilder();

    public SBBuilder add(String... parts) {
        for (String p : parts) {
            sb.append(p).append(' '); // char is even faster here! ;)
        }
        return this;
    }

    public String build() {
        return sb.toString();
    }
}

Here's an articleon the subject.

这是一篇关于这个主题的文章

Hope it helps! :)

希望能帮助到你!:)

回答by Johan

Just add the space yourself, it's easy enough, as per your own example.

只需自己添加空间,这很容易,根据您自己的示例。

回答by Dave Webb

Can you not create a new class which wraps around StringBufferand add an appendWithTrailingSpace()method?

您不能创建一个环绕StringBuffer并添加appendWithTrailingSpace()方法的新类吗?

CustomStringBuffer str = new CustomStringBuffer();
str.appendWithTrailingSpace("string value");

(Although you may want to call your method something a little shorter.)

(尽管您可能希望将您的方法调用得更短一些。)

回答by Dimo

StringBuffer is final. You cannot derive from it. The Best solution really is to add the padding for yourself. Write a method for it and use a PADDING-Constant so that you can easily change it, or better put it in a parameter.

StringBuffer 是最终的。你不能从中获得。最好的解决方案确实是为自己添加填充。为它编写一个方法并使用 PADDING-Constant 以便您可以轻松更改它,或者更好地将其放入参数中。

回答by grom

You should be using StringBuilder.

您应该使用StringBuilder

Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations.

在可能的情况下,建议优先使用此类而不是 StringBuffer,因为在大多数实现下它会更快。

回答by Guvante

Another possibility is that StringBuilder objects return themselves when you call append, meaning you can do:

另一种可能性是 StringBuilder 对象在您调用 append 时返回自身,这意味着您可以执行以下操作:

str.append("string value").append(" ");

Not quite as slick, but it is probably an easier solution than the + " " method.

不那么圆滑,但它可能是比 + " " 方法更简单的解决方案。

Another possibility is to build a wrapper class, like PaddedStringBuilder, that provides the same methods but applies the padding you want, since you can't inherit.

另一种可能性是构建一个包装类,如 PaddedStringBuilder,它提供相同的方法,但应用您想要的填充,因为您不能继承。