简体   繁体   English

在PrintWriter中使用printf()可变字符串宽度

[英]Variable width of strings using printf() in PrintWriter

I am trying to achieve even indentation in my output. 我正在尝试使输出缩进。 So that even if the strings vary in length, the width between the strings will continue to match. 这样,即使字符串的长度不同,字符串之间的宽度也将继续匹配。 What I mean is if I want to print a text file with a person's first name, age, and weight, but I want the indentation to remain even 我的意思是,如果我想打印一个人的名字,年龄和体重的文本文件,但我希望缩进量保持不变

Ryan       1          1
Alexander 25        180
Ashish P. 51        217
Ben       19        130

I know that a fixed width will not work because the name can be very long or short 我知道固定宽度无效,因为名称可能太长或太短

writer.printf("%s%10d%10d", name, age, weight);

I am doing this using the PrintWriter.printf(), although I imagine it applies to System.out.printf() and .format() as well. 我正在使用PrintWriter.printf()进行此操作,尽管我认为它也适用于System.out.printf()和.format()。

You may try to use tabulators to separate each field (\\t char). 您可以尝试使用制表符分隔每个字段(\\ t char)。

writer.printf("%s\t%d\t%d", name, age, weight);

But this may not work well, if the difference between length of shortest and longest name is bigger then the tabulator size. 但是,如果最短名称和最长名称的长度之间的差异较大,则制表符的大小可能不起作用。 In this case you are out of luck and you will have to implement the logic yourself. 在这种情况下,您不走运,您将必须自己实现逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM