【问题标题】:Formatting within a string [duplicate]在字符串中格式化[重复]
【发布时间】:2013-12-10 20:46:28
【问题描述】:

在一个方法中,我有以下代码:

s = s + (items[i] + ":" + numItems[i]+" @ "+prices[i]+" cents each.\n");

哪些输出:

Candy:      5 @ 50 cents each.
Soda:     3 @ 10 cents each.

等等。 . .

在这一行中,我如何获得 5、3 等。 .互相排成一行,这样:

Candy:      5 @ 50 cents each.
Soda:       3 @ 10 cents each.

这是toString() 方法的一部分,所以我不能用System.out.printf 来做

【问题讨论】:

  • String.format(),工作原理与printf相同,但返回一个字符串而不是输出它..

标签: java format


【解决方案1】:

可以使用String.format() 和Formatter 类。

下面的代码会输出类似这样的东西

 /*
 Sample Text    #
     Sample Text#
 */

代码

 public static String padRight(String s, int n) {
    return String.format("%1$-" + n + "s", s);  
 }

 public static String padLeft(String s, int n) {
     return String.format("%1$" + n + "s", s);  
 }

 public static void main(String args[]) throws Exception {
    System.out.println(padRight("Sample Text", 15) + "#");
    System.out.println(padLeft("Sample Text", 15) + "#");
 }

更多用于格式化的 sn-p

 String.format("%5s", "Hi").replace(' ', '*');
 String.format("%-5s", "Bye").replace(' ', '*');
 String.format("%5s", ">5 chars").replace(' ', '*');

输出:

 ***Hi
 Bye**
 >5*chars

除了这个 Apache StringUtils API 之外,还有很多方法,比如 rightPad、leftPad 可以做到这一点。 Link

【讨论】:

    【解决方案2】:

    您可以在 toString() 中使用制表符 \t

    这是一个例子:

    System.out.println("Candy \t 5");
    System.out.println("Soda \t 10");
    
    Candy    5
    Soda     10
    

    所以你的情况

    s = s + (items[i] + ": \t" + numItems[i]+" @ "+prices[i]+" cents each.\n");
    

    【讨论】:

      【解决方案3】:

      您可以使用 \t 来插入标签。

      【讨论】:

        【解决方案4】:

        试试这个

        s = s + (makeFixedLengthString(items[i]) + ":" + numItems[i]+" @ "+prices[i]+" cents each.\n");
        
        public String makeFixedLengthString(String src){
                int len = 15;
                for(int i = len-src.length(); i < len; i++)
                    src+=" ";
                return src;
        }
        

        【讨论】:

          猜你喜欢
          • 2017-10-27
          • 1970-01-01
          • 2020-07-04
          • 2015-01-07
          • 2011-05-17
          • 2014-09-24
          • 2012-01-07
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多