【问题标题】:how to string pad with variables instead of hard coded numbers inside %s in javajava - 如何在java中的%s内使用变量而不是硬编码数字字符串填充
【发布时间】:2017-09-04 01:32:32
【问题描述】:

我正在尝试用空格将字符串填充到右侧,以使不同的字符串长度在同一点对齐。我尝试使用以下方法来做到这一点。但是,我不知道如何在 %s 中使用变量 namePad,就好像我们使用实数一样(例如使用 %(namePad)s 而不是 %5s)

 public String toString() {
    int namePad = 10-name.length();
    return String.format(id + " -" + " %-5s" + "%10s" , name, "");
}

输出样本:

All customers:
1 - Bill Gates          *// padding all the strings to here
2 - Trump           *  
3 - Tali           *            
4 - James Bond          *         

【问题讨论】:

    标签: java string text-alignment


    【解决方案1】:

    您可以使用"%-"+namePad+"s" 代替"%-5s"

    虽然,我不确定您是否真的需要该变量。您正在使用String.format,但没有提供任何变量来格式化,所以试试这个。

    String.format("%d - %-21s", id, name);
    

    或者,和以前一样

    int pad = 21;
    return String.format("%d - %-"+pad+"s*", id, name);
    

    例如,(添加了* 以显示填充)

    static class Person {
        int id;
        String name;
    
        public Person(int id, String name) {
            this.id = id; this.name = name;
        }
    
        public String toString() {
            return String.format("%d - %-21s*", id, name);
        }
    }
    
    public static void main (String[] args) throws java.lang.Exception
    {
        Person[] people = { 
            new Person(1, "Bill Gates"),
            new Person(2, "Trump"),
            new Person(3, "Tail"), 
            new Person(4, "James Bond")
        };
    
        for (Person p : people) {
            System.out.println(p);
        }
    }
    

    输出

    1 - Bill Gates           *
    2 - Trump                *
    3 - Tail                 *
    4 - James Bond           *
    

    【讨论】:

    • 感谢帮了大忙,namePad 为 0 时它不起作用,否则它确实起作用,但第二种解决方案更好
    • 嗯,是的,如果为零,就没有空间打印字符串了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-31
    • 2010-09-28
    • 2012-06-11
    • 1970-01-01
    • 2019-11-21
    • 1970-01-01
    相关资源
    最近更新 更多