String 类有一个强大的字符串格式化方法 format()。下面是常用的方法总结。
一、占位符类型
位符 "%" 后面的字母决定了其接受的实际参数的类型。占位符类型有下面几种:
字母适用参数类型说明
| %a | 浮点数 | 以16进制输出浮点数 |
| %b / %B | 任意值 | 如果参数为 null 则输出 false,否则输出 true |
| %c / %C | 字符或整数 | 输出对应的 Unicode 字符 |
| %d | 整数 | 对整数进行格式化输出 |
| %e / %E | 浮点数 | 以科学记数法输出浮点数 |
| %f | 浮点数 | 对浮点数进行格式化输出 |
| %g / %G | 浮点数 | 以条件来决定是否以科学记数法方式输出浮点数 |
| %h / %H | 任意值 | 以 16 进制输出参数的 hashCode() 返回值 |
| %o | 整数 | 以8进制输出整数 |
| %s / %S | 字符串 | 对字符串进行格式化输出 |
| %t | 日期时间 | 对日期时间进行格式化输出 |
| %x / %X | 整数 | 以16进制输出整数 |
| %n | 无 | 换行符 |
| %% | 无 | 百分号本身 |
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"));// 输出 "Hello , world"System.out.println(String.format("%-10s, world", "Hello123456789"));// 输出 "Hello123456789, world"System.out.println(String.format("%-8d", 123));// 输出 "123 "System.out.println(String.format("%-8d", 123456789));// 输出 "123456789"// 补齐0并对齐(仅对数字有效),入参超过模版长度的,全量输出System.out.println(String.format("%08d", 123));// 输出 "00000123"System.out.println(String.format("%08d", 123456789));// 输出 "123456789"// String format3 = String.format("%-08d", 123);// 错误!不允许在右边补齐 0// 输出最多N个入参字符System.out.println(String.format("%.2s", "Hello, world"));// 输出 "He"System.out.println(String.format("%.5s...", "Hello, world"));// 输出 "Hello..."// 输出最多N个入参字符,总长度不足10,左侧补0System.out.println(String.format("%10.6s...", "Hello, world"));// 输出 " Hello,..."// 输出逗号分隔数字System.out.println(String.format("%,d", 1234567));// 输出 "1,234,567"