4

Suppose I want to print "Item" and its "price" in some specific format like

abc           2
asdf          4
qwer xyz      5

AND 2, 4, 5 must be like in one column.

For that i tried-

StringBuilder sb = new StringBuilder();

sb.append(String.format("%s%25s", "abc","2"));
sb.append(String.format("%s%25s", "asdf","4"));
sb.append(String.format("%s%25s", "qwer xyz","5"));

tv.setText(sb.toString());   //tv is a text view

but the output is -

abc             2
asdf             4
qwer xyz             5

I want "abc" and after 25 spaces i want "5" but it counts 25 spaces from abc not from the start

2 Answers 2

5

You mixed up the order try this:

StringBuilder sb = new StringBuilder();

sb.append(String.format("%-25s%s", "abc","2"));
sb.append(String.format("%-25s%s", "asdf","4"));
sb.append(String.format("%-25s%s", "qwer xyz","5"));

tv.setText(sb.toString());   //tv is a text view

That minus sign before the 25 means to invert the alignment of your text. The last step is to use a monospace font. You can achieve that with this line:

tv.setTypeface(Typeface.MONOSPACE);
Sign up to request clarification or add additional context in comments.

Comments

1

You can use tab in every line. I hope it will work.

StringBuilder sb = new StringBuilder();

    sb.append(String.format("%s%25s\t", "abc","2"));
    sb.append(String.format("%s%25s\t", "asdf","4"));
    sb.append(String.format("%s%25s\t", "qwer xyz","5"));

    tv.setText(sb.toString());

1 Comment

Sorry but this is nonsense. It would just add to the output above a tab at the end.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.