Java中String.format()方法详解

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_37896194/article/details/96478305
  • 前言

        从 Java 5.0 开始,String 类新增了一个强大的字符串格式化方法 format()。这个方法到现在用的人还是不多,实在是一种浪费。下面就是这个方法的使用方式,将来要用到格式化文本的时候,可能就不需要再借用第三方类库或自己去实现了。

  • 例子

String stringToken= String.format("https://api.weixin.qq.com/sns/oauth2/access_token?"
			+ "appid=%s&secret=%s&code=%s&grant_type=authorization_code", appId, appSecret, code);

  •  解释

    • 这个方法第一个参数是格式串,后面的参数都是格式串的参数,用于替换格式串中的占位符。
    • 占位符以 "%x" 的形式表示,不同的参数类型要用不同的字母。后面会具体介绍。
    • String.format() 返回值类型为字符串,也就是格式化的结果。
  • 优点

    • 增强了代码的可读性。

  • 注意

    • 这个方法的执行效率低于StringBuilder.append(),因此,建议字符串的拼接不是很多时使用String.format()方法。如果字符串很多则建议使用StringBuilder.append()方法。

  • 例子

    public class StringDemo {
    	public static void main(String[] args) {
                //System.nanoTime():获取当前时间的纳秒值
    		Long time1 = System.nanoTime();
    		String string = String.format("https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code", "张","无","忌");
    		Long time2 = System.nanoTime();
    		System.out.println(string+"\nString.format的执行时间:"+(time2-time1)+"ns");
    		
    		Long time3 = System.nanoTime();
    		StringBuilder sb = new StringBuilder ();
    		sb.append("https://api.weixin.qq.com/sns/oauth2/access_token?appid=").append("张").append("&secret=").append("无").append("&code=")
    		.append("忌").append("&grant_type=authorization_code");
    		Long time4 = System.nanoTime();
    		System.out.println(sb.toString()+"\nStringBuilder的执行时间:"+(time4-time3)+"ns");
    	}
    }
  • 结果 

https://api.weixin.qq.com/sns/oauth2/access_token?appid=张&secret=无&code=忌&grant_type=authorization_code
String.format的执行时间:19683180ns
https://api.weixin.qq.com/sns/oauth2/access_token?appid=张&secret=无&code=忌&grant_type=authorization_code
StringBuilder的执行时间:6564ns
  • 常用的类型以及转换符

转换符

详细说明

示例

%s

字符串类型

“喜欢请收藏”

%c

字符类型

‘m’

%b

布尔类型

true

%d

整数类型(十进制)

88

%x

整数类型(十六进制)

FF

%o

整数类型(八进制)

77

%f

浮点类型

8.888

%a

十六进制浮点类型

FF.35AE

%e

指数类型

9.38e+5

%g

通用浮点类型(f和e类型中较短的)

不举例(基本用不到)

%h

散列码

不举例(基本用不到)

%%

百分比类型

%(%特殊字符%%才能显示%)

%n

换行符

不举例(基本用不到)

%tx

日期与时间类型(x代表不同的日期与时间转换符)

不举例(基本用不到)


猜你喜欢

转载自blog.csdn.net/qq_37896194/article/details/96478305