Java 是否支持多行字符串?

新手上路,请多包涵

来自 Perl,我肯定错过了在源代码中创建多行字符串的“here-document”方法:

 $string = <<"EOF"  # create a three-line string
text
text
text
EOF

在 Java 中,当我从头开始连接多行字符串时,我必须在每一行上使用繁琐的引号和加号。

有哪些更好的选择?在属性文件中定义我的字符串?

编辑:两个答案说 StringBuilder.append() 比加号更可取。谁能详细说明他们为什么这么认为?对我来说,它看起来并不更可取。我正在寻找解决多行字符串不是一流语言结构这一事实的方法,这意味着我绝对不想用方法调用替换一流语言结构(字符串与加号连接)。

编辑:为了进一步澄清我的问题,我根本不关心性能。我担心可维护性和设计问题。

原文由 skiphoppy 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.3k
2 个回答

Stephen Colebourne 创建了一个在 Java 7 中添加多行字符串的 提案

此外,Groovy 已经支持 多行字符串

原文由 Paul Morie 发布,翻译遵循 CC BY-SA 3.0 许可协议


注意:此答案适用于 Java 14 及更早版本。

Java 15 中引入了文本块(多行文字)。有关详细信息,请参阅 此答案


听起来您想做一个多行文字,这在 Java 中不存在。

您最好的选择是将 + 组合在一起的字符串。人们提到的其他一些选项(StringBuilder、String.format、String.join)只有在您从字符串数组开始时才是可取的。

考虑一下:

 String s = "It was the best of times, it was the worst of times,\n"
         + "it was the age of wisdom, it was the age of foolishness,\n"
         + "it was the epoch of belief, it was the epoch of incredulity,\n"
         + "it was the season of Light, it was the season of Darkness,\n"
         + "it was the spring of hope, it was the winter of despair,\n"
         + "we had everything before us, we had nothing before us";

对比 StringBuilder

 String s = new StringBuilder()
           .append("It was the best of times, it was the worst of times,\n")
           .append("it was the age of wisdom, it was the age of foolishness,\n")
           .append("it was the epoch of belief, it was the epoch of incredulity,\n")
           .append("it was the season of Light, it was the season of Darkness,\n")
           .append("it was the spring of hope, it was the winter of despair,\n")
           .append("we had everything before us, we had nothing before us")
           .toString();

对比 String.format()

 String s = String.format("%s\n%s\n%s\n%s\n%s\n%s"
         , "It was the best of times, it was the worst of times,"
         , "it was the age of wisdom, it was the age of foolishness,"
         , "it was the epoch of belief, it was the epoch of incredulity,"
         , "it was the season of Light, it was the season of Darkness,"
         , "it was the spring of hope, it was the winter of despair,"
         , "we had everything before us, we had nothing before us"
);

与 Java8 String.join()

 String s = String.join("\n"
         , "It was the best of times, it was the worst of times,"
         , "it was the age of wisdom, it was the age of foolishness,"
         , "it was the epoch of belief, it was the epoch of incredulity,"
         , "it was the season of Light, it was the season of Darkness,"
         , "it was the spring of hope, it was the winter of despair,"
         , "we had everything before us, we had nothing before us"
);

如果您想要特定系统的换行符,您需要使用 System.lineSeparator() ,或者您可以使用 %nString.format

另一种选择是将资源放在一个文本文件中,然后只读取该文件的内容。这对于非常大的字符串来说是更可取的,以避免不必要地膨胀你的类文件。

原文由 Kip 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏