在没有串联的情况下在另一个字符串中插入Java字符串?

2022-09-01 19:37:42

在Java中有没有更优雅的方法来做到这一点?

String value1 = "Testing";  
String test = "text goes here " + value1 + " more text";

是否可以将变量直接放在字符串中并计算其值?


答案 1
   String test = String.format("test goes here %s more text", "Testing");

是你能用Java写的最接近的东西


答案 2

更优雅的方式可能是:

 String value = "Testing"; 
 String template = "text goes here %s more text";
 String result = String.format(template, value);

或者使用 MessageFormat:

 String template = "text goes here {0} more text";
 String result = MessageFormat.format(template, value);

请注意,如果这样做是为了记录,那么当日志行低于阈值时,可以避免执行此操作的成本。例如,对于 SLFJ

以下两行将产生完全相同的输出。但是,在禁用日志记录语句的情况下,第二种形式的性能将比第一种形式的性能至少高出 30 倍。

logger.debug("The new entry is "+entry+".");
logger.debug("The new entry is {}.", entry);