gpt4 book ai didi

java - Java 是否支持多行字符串?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:37:16 26 4
gpt4 key购买 nike

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

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

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

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

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

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

最佳答案


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

文本 block (多行文字)是在 Java 15 中引入的。参见 this answer了解详情。


听起来你想做一个多行文字,这在 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(),或者您可以在 String 中使用 %n。格式

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

关于java - Java 是否支持多行字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34285634/

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