夯实基础:将String.format格式化讲解的一清二楚

(34) 2023-10-24 20:12

Hi,大家好,我是编程小6,很荣幸遇见你,我把这些年在开发过程中遇到的问题或想法写出来,今天说一说夯实基础:将String.format格式化讲解的一清二楚,希望能够帮助你!!!。

目录

  • 一、引言
  • 二、重装
  • 三、占位符
  • 四、超过一项以上的参数时
  • 五、转换符
  • 六、转换符的标志
  • 七、对字符串进行格式化
  • 八、对整数进行格式化
  • 九 、对浮点数进行格式化
  • 十、对日期时间进行格式化

一、引言

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是必要的. 格式化说明的顺序是有规定的,必须要以这个顺序章指定.

夯实基础:将String.format格式化讲解的一清二楚_https://bianchenghao6.com/blog__第1张

实例:

夯实基础:将String.format格式化讲解的一清二楚_https://bianchenghao6.com/blog__第2张

四、超过一项以上的参数时

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

 
int one = 123456789;
 double two = 123456.789;
 String s = String.format("第一个参数:%,d 第二个参数:%,.2f", one, two);
 System.out.println(s);
夯实基础:将String.format格式化讲解的一清二楚_https://bianchenghao6.com/blog__第3张

五、转换符

夯实基础:将String.format格式化讲解的一清二楚_https://bianchenghao6.com/blog__第4张

六、转换符的标志

夯实基础:将String.format格式化讲解的一清二楚_https://bianchenghao6.com/blog__第5张

七、对字符串进行格式化

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

 
String raw = "hello word";
 
String str = String.format("|%-15s|", raw);
 System.out.println(str);
夯实基础:将String.format格式化讲解的一清二楚_https://bianchenghao6.com/blog__第6张

八、对整数进行格式化

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

int num = -1000;
String str = String.format("%(,d", num);
System.out.println(str);
夯实基础:将String.format格式化讲解的一清二楚_https://bianchenghao6.com/blog__第7张

九 、对浮点数进行格式化

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));
夯实基础:将String.format格式化讲解的一清二楚_https://bianchenghao6.com/blog__第8张

十、对日期时间进行格式化

日期的转换符

夯实基础:将String.format格式化讲解的一清二楚_https://bianchenghao6.com/blog__第9张

时间的转换符

夯实基础:将String.format格式化讲解的一清二楚_https://bianchenghao6.com/blog__第10张

实例

夯实基础:将String.format格式化讲解的一清二楚_https://bianchenghao6.com/blog__第11张

夯实基础:将String.format格式化讲解的一清二楚_https://bianchenghao6.com/blog__第12张

今天的分享到此就结束了,感谢您的阅读,如果确实帮到您,您可以动动手指转发给其他人。

上一篇

已是最后文章

下一篇

已是最新文章

发表回复