String.format()详细用法

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"));// 输出 "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,左侧补0
System.out.println(String.format("%10.6s...", "Hello, world"));// 输出 "    Hello,..."
 
// 输出逗号分隔数字
System.out.println(String.format("%,d", 1234567));// 输出 "1,234,567"


                        
原文链接:

https://blog.csdn.net/danxiaodeshitou/article/details/130786587https://blog.csdn.net/YHLSunshine/article/details/132673650

  • 19
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值