前言:有次面试的时候,面试官让我写个字符串连接的方法,我很耿直的使用"+"去连接.后来面试官问我有没有用过String.format().我心底想不一字符串的连接么,需要这么花哨吗?后来在源码里发现都是使用String.format()这个方法连接字符串.
String.format有两种方式重载.
public static String format(String format, Object... args) {
return new Formatter().format(format, args).toString();
}
public static String format(Locale l, String format, Object... args) {
return new Formatter(l).format(format, args).toString();
}
第二种方式相比于第一种方式指定系统的语言和国家代码.一般直接使用第一种方式.
使用第一种方式时,默认使用本地的国家代码
public Formatter() {
this(Locale.getDefault(Locale.Category.FORMAT), new StringBuilder());
}
我们点击源码发现其实也是new的StringBuilder去构造的字符串,然后返回.
常用数据类型转换为字符串
转换符 | 数据类型 | 示例 |
%s | 字符串(String) | "测试" |
%c | 字符类型(Char) | 'w' |
%b | 布尔类型(Boolean) | true |
%d | 整数类型(Int) | 20 |
%f | 浮点类型(Float) | 20.2 |
%n | 转换符 | |
F | “年-月-日”格式 | 2018-12-28 |
主要用到就是这些.