Link to home
Start Free TrialLog in
Avatar of shragi
shragiFlag for India

asked on

stringbuffer left justify

I am creating a file with mostly static text,
but i had a problem when i want to preserve space.

I wrote the below code for creating file..

StringBuffer bufferText = new StringBuffer();
bufferText .append(String.format("%2s", "AB" ));
bufferText .append(String.format("%4s", "2012"));
bufferText .append(String.format("%1s", " "));
bufferText .append(String.format("%2s", "CD" ));
bufferText .append(String.format("%20s", "Hi Experts"));
bufferText .append(String.format("%2s", "EF" ));

The file was created with the below text

AB2012 CD          HI ExpertsEF

but i want the output to be left justified...like below...

AB2012 CDHI Experts          EF

I mean in the below line of code the string length is 20 but the string "HI Experts" is just 10 so the remaining 10 characters are spaces... i want those ten characters to be after "HI Experts" not before "HI Experts"

bufferText .append(String.format("%20s", "Hi Experts"));

I see that stringbuffer by default appends the string with right justification can i change it to left justification....


is there a way to achieve this... other than me specifying
bufferText .append(String.format("%20s", "HI Experts          "));
i dont want to do it in the above method because sometimes the string length can be 200 and my actual string can be only 20 characters... so i dont want to count 180 spaces...
ASKER CERTIFIED SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of shragi

ASKER

that solved my problem.... i ahve another question...how to add only spaces... using append...

i mean if i want to add some 20 spaces i am using the below line
bufferText .append(String.format("%-20s", "                    "));

is there any other way to do this...
You don't need to add spaces - that's the whole point of formatting. An empty String will suffice
Avatar of shragi

ASKER

excellent thank you :)
:)