如何在android中获取特定格式的字符串

时间:2014-02-04 09:26:34

标签: java string-formatting

假设我想以某种特定格式打印“Item”及其“price”,如

abc           2
asdf          4
qwer xyz      5

AND 2,4,5必须像一列一样。

为此我试过 -

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

输出 -

abc             2
asdf             4
qwer xyz             5

我想要“abc”,在25个空格之后我想要“5”,但它从abc开始计算25个空格而不是从开始

2 个答案:

答案 0 :(得分:5)

你混淆了订单试试这个:

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

25之前的减号表示反转文本的对齐方式。最后一步是使用等宽字体。你可以用这一行来实现这个目标:

tv.setTypeface(Typeface.MONOSPACE);

答案 1 :(得分:1)

您可以在每一行使用标签。我希望它能奏效。

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