java输出字符串右对齐_Java Language

Example

The method PrintWriter.format (called through System.out.format) can be used to print aligned strings in console. The method receives a String with the format information and a series of objects to format:

String rowsStrings[] = new String[] {"1",

"1234",

"1234567",

"123456789"};

String column1Format = "%-3s"; // min 3 characters, left aligned

String column2Format = "%-5.8s"; // min 5 and max 8 characters, left aligned

String column3Format = "%6.6s"; // fixed size 6 characters, right aligned

String formatInfo = column1Format + " " + column2Format + " " + column3Format;

for(int i = 0; i < rowsStrings.length; i++) {

System.out.format(formatInfo, rowsStrings[i], rowsStrings[i], rowsStrings[i]);

System.out.println();

}

Output:

1 1 1

1234 1234 1234

1234567 1234567 123456

123456789 12345678 123456

Using format strings with fixed size permits to print the strings in a table-like appearance with fixed size columns:

String rowsStrings[] = new String[] {"1",

"1234",

"1234567",

"123456789"};

String column1Format = "%-3.3s"; // fixed size 3 characters, left aligned

String column2Format = "%-8.8s"; // fixed size 8 characters, left aligned

String column3Format = "%6.6s"; // fixed size 6 characters, right aligned

String formatInfo = column1Format + " " + column2Format + " " + column3Format;

for(int i = 0; i < rowsStrings.length; i++) {

System.out.format(formatInfo, rowsStrings[i], rowsStrings[i], rowsStrings[i]);

System.out.println();

}

Output:

1 1 1

123 1234 1234

123 1234567 123456

123 12345678 123456

Format strings examples

%s: just a string with no formatting

%5s: format the string with a minimum of 5 characters; if the string is shorter it will be padded to 5 characters and right aligned

%-5s: format the string with a minimum of 5 characters; if the string is shorter it will be padded to 5 characters and left aligned

%5.10s: format the string with a minimum of 5 characters and a maximum of 10 characters; if the string is shorter than 5 it will be padded to 5 characters and right aligned; if the string is longer than 10 it will be truncated to 10 characters and right aligned

%-5.5s: format the string with a fixed size of 5 characters (minimum and maximum are equals); if the string is shorter than 5 it will be padded to 5 characters and left aligned; if the string is longer than 5 it will be truncated to 5 characters and left aligned

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值