String 类有一个强大的字符串格式化方法 format()。下面是常用的方法总结。
一、占位符类型
String formatted = String.format("%s今年%d岁。", "小李", 25); // "小李今年25岁。"
二、字符串和整数格式化
// 将第二个入参拼接到模板中,入参长度如果不足10 左侧用空格补齐,超过10全量输出
System.out.println(String.format("%10s, world", "Hello"));// 输出 " Hello, world"
System.out.println(String.format("%10s, world", "Hello12345689"));// 输出 "Hello12345689, world"
// 要格式化的参数为数字类型,入参长度如果不足8 左侧用空格补齐,超过10全量输出
System.out.println(String.format("%8d", 123));// 输出 " 123"
System.out.println(String.format("%8d", 123456789));// 输出 " 123"
// 补齐空格并左对齐,入参长度如果不足10,右侧补齐空格,长度超过10全量输出
System.out.println(String.format("%-10s, world", "Hello