8

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

Jean Paul Galea
  • 1,321
  • 4
  • 18
  • 26
  • can you show us some of your actual code where you are appending items? Because maybe there is another way of building the string that would make more sense. – grom Sep 30 '08 at 08:36
  • hmm, I basically have a do-while loop that appends an input to a string and the loop exists when the input ends with a ";" – Jean Paul Galea Sep 30 '08 at 08:44
  • It's probably more elegant (and quicker) to use a regular expression to determine whether to run the query or not, e.g.: if (query.matches(".*;\s*")) { – Chris Carruthers Sep 30 '08 at 13:09
  • Wouldn't it be better to check input ends with ';' instead of converting the buffer to a string each time? – grom Oct 01 '08 at 08:32
  • This might help you: http://stackoverflow.com/questions/63150/whats-the-best-way-to-build-a-string-of-delimited-items-in-java – Vinko Vrsalovic Sep 30 '08 at 08:21

6 Answers6

10

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

kolrie
  • 12,562
  • 14
  • 64
  • 98
6

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.

grom
  • 15,842
  • 19
  • 64
  • 67
4

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.

Dimo
  • 41
  • 1
3

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

David Webb
  • 190,537
  • 57
  • 313
  • 299
  • That should not be possible. StringBuffer is final, i.e. no derivation from it. – Burkhard Sep 30 '08 at 08:33
  • How does an incorrect answer get accepted and worse upvoted? Its not possible to subclass StringBuffer – grom Sep 30 '08 at 08:37
  • Whoops. You're right. I've changed the answer to read "wraps around" rather than "extends". Sadly it's not as neat this way. – David Webb Sep 30 '08 at 08:38
  • I actually think that wrapping the string buffer is just fine. Subclassing is not really appropriate in this case - you are really creating a 'builder' object using composition. Nothing wrong with it, and if the decide later to use a different implementation you can... – Kevin Day Oct 01 '08 at 03:52
2

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

Johan
  • 1,940
  • 1
  • 13
  • 18
  • yeah it's easy, but I find it dirty. And if I happen to change my mind and instead of a space, I want some other character, I'd have to go through several lines instead of one! – Jean Paul Galea Sep 30 '08 at 08:18
  • although yeah, I could do this: String bar = " "; str.append(foo + bar); but still I want to find out if there's a better way of doing it – Jean Paul Galea Sep 30 '08 at 08:19
1

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.

Guvante
  • 18,775
  • 1
  • 33
  • 64