字符串操作

一、概述

1. 字符串占位符

以前写日志输出都是用“+”号拼接字符串,简单的还凑合,但是描述信息稍微难看一点,就不知道啥玩意了。今天,又需要写日志了,想着也不能天天都是小学生,只会使用加号,所以忙里偷闲,研究了下。

// 字符串占位
// 方法一:使用String的静态方法format
String format = String.format(" %s * %s = %s", "2", "3", 5);
// 2 * 3 = 5
System.out.println("format: " + format);

// 方法二:功能强大,支持指定类型和格式,性能更好,但是需要指定参数位置
// 参考:https://blog.csdn.net/GarfieldEr007/article/details/89397843
String format1 = MessageFormat.format(" {0} * {1} = {2}", "2", "3", 5);
//  2 * 3 = 5
System.out.println("format1: " + format1);

// 方法三:日志输出中使用占位符
try {
    int a = 2 / 0;
} catch (Exception e) {
    log.info(" {} * {} = {}", "2", "3", 5, e);
}

// 方法四: 没有换行符
// 2 * 3 = 5
System.out.printf(" %s * %s = %s", "2", "3", 5);
System.out.println();
原文地址:https://www.cnblogs.com/shiyun32/p/12557746.html