Java多行字符串

来自Perl,我确定缺少在源代码中创建多行字符串的“here-document”方法:

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

在Java中,我必须在每行都有繁琐的引号和加号,因为我从头开始连接多行字符串。

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

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

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


Stephen Colebourne提出了在Java 7中添加多行字符串的建议。

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


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

你最好的选择将是只是+ 'd在一起的字符串。 人们提到的一些其他选项(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("%sn%sn%sn%sn%sn%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.getProperty("line.separator") ,或者你可以在String.format使用%n

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


在Eclipse中,如果打开选项“粘贴到字符串文本时转义文本”(在首选项> Java>编辑器>键入中)并粘贴引号内的多行字符串,则会自动为所有字符添加"n" +你的线条。

String str = "paste your text here";
链接地址: http://www.djcxy.com/p/20903.html

上一篇: Java multiline string

下一篇: Why does the JVM allow to set the "high" value for the IntegerCache, but not the "low"?