gpt4 book ai didi

java - 在java代码中模板化多行字符串的简单方法

转载 作者:行者123 更新时间:2023-12-03 02:02:27 30 4
gpt4 key购买 nike

我经常遇到以下情况:我有很长的多行字符串,必须在其中注入(inject)属性 - 例如像模板之类的东西。但我不想在我的项目中包含完整的模板引擎(例如velocity 或freemarker)。

如何以简单的方式完成此操作:

String title = "Princess";
String name = "Luna";
String community = "Stackoverflow";

String text =
"Dear " + title + " " + name + "!\n" +
"This is a question to " + community + "-Community\n" +
"for simple approach how to code with Java multiline Strings?\n" +
"Like this one.\n" +
"But it must be simple approach without using of Template-Engine-Frameworks!\n" +
"\n" +
"Thx for ...";

最佳答案

使用 Java 15+:

String title = "Princess";
String name = "Luna";
String community = "Stackoverflow";

String text = """
Dear %s %s!
This is a question to %s-Community
for simple approach how to code with Java multiline Strings?
""".formatted(title, name, community);

关于java - 在java代码中模板化多行字符串的简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21232185/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com