Java多行字符串
来自Perl,我肯定缺少在源代码中创建多行字符串的“ here-document”方法:
$string = <<"EOF" # create a three-line stringtext
text
text
EOF
在Java中,当我从头开始连接多行字符串时,必须在每行上加上繁琐的引号和加号。
有哪些更好的选择?在属性文件中定义我的字符串?
编辑:两个答案说StringBuilder.append()比加号法更可取。任何人都可以解释为什么会这样吗?对我来说,这似乎一点都不可取。我正在寻找一种解决方法,即多行字符串不是一流的语言构造,这意味着我绝对不希望用方法调用替换一流的语言构造(带plus的字符串连接)。
编辑:为了进一步阐明我的问题,我根本不关心性能。我担心可维护性和设计问题。
回答:
最好的选择是将字符串+
组合在一起。人们提到的其他一些选项(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()
,也可以%n在中使用String.format
。
另一个选择是将资源放在文本文件中,然后仅读取该文件的内容。对于非常大的字符串,这将是更好的选择,以避免不必要地使您的类文件膨胀。
以上是 Java多行字符串 的全部内容, 来源链接: utcz.com/qa/436247.html