How to get string in specific format in android

java, string-formatting

Solution

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

Problem

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

Original source