String.format() 图文详解,写得非常好!

Java技术栈

共 1910字,需浏览 4分钟

 · 2020-08-24

Java技术栈

www.javastack.cn

关注阅读更多优质文章



作者:潘佳琦
链接:https://segmentfault.com/a/1190000019350486

引言

String类的format()方法用于创建格式化的字符串以及连接多个字符串对象。熟悉C语言应该记得C语言的sprintf()方法,两者有类似之处。

format()方法有两种重载形式。

重载

// 使用当前本地区域对象(Locale.getDefault()),制定字符串格式和参数生成格式化的字符串
String String.format(String fmt, Object... args);

// 自定义本地区域对象,制定字符串格式和参数生成格式化的字符串
String String.format(Locale locale, String fmt, Object... args);

占位符

格式化说明最多会有5个部分(不包括%符号) . 下面的[]符号里面都是选择性的项目,因此只有%与type是必要的. 格式化说明的顺序是有规定的,必须要以这个顺序章指定.

实例:

超过一项以上的参数时

把新的参数加到后面,因此会有3个参数来调用format()而不是两个,并且在第一个参数中,也就是格式化串中,会有两个不同的格式化设定,也就是两个%开头的字符组合,第二个会应用在第一个%上面,第三个参数会用在第二%上,也就是参数会依照顺序应用在%上面" 。

int one = 123456789;
double two = 123456.789;
String s = String.format("第一个参数:%,d 第二个参数:%,.2f", one, two);
System.out.println(s);

转换符

转换符的标志

对字符串进行格式化

示例——将"hello"格式化为"hello  "(左对齐)

String raw = "hello word";
String str = String.format("|%-15s|", raw);
System.out.println(str);

对整数进行格式化

示例——将-1000显示为(1,000)

int num = -1000;String str = String.format("%(,d", num);
System.out.println(str);

对浮点数进行格式化

double num = 123.456789;
System.out.print(String.format("浮点类型:%.2f %n", num));
System.out.print(String.format("十六进制浮点类型:%a %n", num));
System.out.print(String.format("通用浮点类型:%g ", num));

对日期时间进行格式化

  • 日期的转换符
  • 时间的转换符
  • 实例
Date date = new Date();
System.out.printf("全部日期和时间信息:%tc%n",date);
System.out.printf("年-月-日格式:%tF%n",date);
System.out.printf("月/日/年格式:%tD%n",date);
System.out.printf("HH:MM:SS PM格式(12时制):%tr%n",date);
System.out.printf("HH:MM:SS格式(24时制):%tT%n",date);
System.out.printf("HH:MM格式(24时制):%tR",date);

最近热文:
1、重磅!《Java开发手册(嵩山版)》最新发布
2、打破你的认知!Java空指针居然还能这样玩
3、盘点 35 个 Apache 顶级项目,我拜服了…
4、Spring Boot 太狠了,一次发布 3 个版本!
5、Spring Boot 如何快速集成 Redis?
6、盘点 6 个被淘汰的 Java 技术,曾经风光过!
7、Spring Boot Redis 实现分布式锁,真香!
8、国人开源了一款小而全的 Java 工具类库
9、公司来了个新同事不会用 Lombok!
10、同事写了个隐藏 bug,我排查了 3 天!
扫码关注Java技术栈公众号阅读更多干货。

点击「阅读原文」获取面试题大全~

浏览 14
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报