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
I think this is handled easier either with a helper method (untested code):
Or even using a Builder pattern with a fluent interface (also untested code):
Here’s an article on the subject.
Hope it helps! 🙂