Java:StringBuffer & 级联

发布于 2024-07-06 13:35:54 字数 836 浏览 13 评论 0原文

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

StringBuffer str = new StringBuffer();

str.append("string value");

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

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

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

并且我有几次调用追加..并且每次我都想添加一个空格。 有没有办法设置对象,以便它在每次追加后自动添加一个空格?

编辑 -

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");

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

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

天赋异禀 2024-07-13 13:35:54

我认为使用辅助方法(未经测试的代码)可以更容易地处理这个问题:

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! ;)
}

或者甚至使用具有流畅接口的构建器模式(也是未经测试的代码):

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();
    }
}

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

希望能帮助到你! :)

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):

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 article on the subject.

Hope it helps! :)

故人如初 2024-07-13 13:35:54

您应该使用 StringBuilder

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

You should be using StringBuilder.

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

遮云壑 2024-07-13 13:35:54

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

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.

此刻的回忆 2024-07-13 13:35:54

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

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

(尽管您可能想将您的方法命名为更短一些。)

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

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

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

自此以后,行同陌路 2024-07-13 13:35:54

只需自己添加空格即可,这很简单,按照您自己的示例即可。

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

扭转时空 2024-07-13 13:35:54

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

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

不太灵活,但它可能是比 + " " 方法更简单的解决方案。

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

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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文