且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

有没有办法使用 SLF4J 样式的格式化函数来构建 Java 字符串?

更新时间:2023-09-06 20:30:22

对于连接字符串一次,旧的可靠"str"+ param + "other str" 完全没问题(它实际上被编译器转换成 StringBuilder).

For concatenating strings one time, the old reliable "str" + param + "other str" is perfectly fine (it's actually converted by the compiler into a StringBuilder).

StringBuilders 主要用于向字符串添加内容,但您无法将它们全部放入一个语句中.以for循环为例:

StringBuilders are mainly useful if you have to keep adding things to the string, but you can't get them all into one statement. For example, take a for loop:

String str = "";
for (int i = 0; i < 1000000; i++) {
    str += i + " "; // ignoring the last-iteration problem
}

这将比等效的 StringBuilder 版本运行得慢得多:

This will run much slower than the equivalent StringBuilder version:

StringBuilder sb = new StringBuilder(); // for extra speed, define the size
for (int i = 0; i < 1000000; i++) {
    sb.append(i).append(" ");
}
String str = sb.toString();

但这两者在功能上是等价的:

But these two are functionally equivalent:

String str = var1 + " " + var2;
String str2 = new StringBuilder().append(var1).append(" ").append(var2).toString();


说了这么多,我的实际答案是:

查看java.text.MessageFormat.来自 Javadocs 的示例代码:


Having said all that, my actual answer is:

Check out java.text.MessageFormat. Sample code from the Javadocs:

int fileCount = 1273;
String diskName = "MyDisk";
Object[] testArgs = {new Long(fileCount), diskName};

MessageFormat form = new MessageFormat("The disk \"{1}\" contains {0} file(s).");

System.out.println(form.format(testArgs));

输出:

磁盘MyDisk"包含 1,273 个文件.

还有一个静态的 format 方法,不需要创建 MessageFormat 对象.

There is also a static format method which does not require creating a MessageFormat object.

所有这些库都将归结为最基本级别的字符串连接,因此它们之间不会有太大的性能差异.

All such libraries will boil down to string concatenation at their most basic level, so there won't be much performance difference from one to another.