shragi
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("%20 s", "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("%20 s", "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("%20 s", "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...
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
bufferText .append(String.format("%4s
bufferText .append(String.format("%1s
bufferText .append(String.format("%2s
bufferText .append(String.format("%20
bufferText .append(String.format("%2s
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("%20
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("%20
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
You don't need to add spaces - that's the whole point of formatting. An empty String will suffice
ASKER
excellent thank you :)
:)
ASKER
i mean if i want to add some 20 spaces i am using the below line
bufferText .append(String.format("%-2
is there any other way to do this...