Java多行字符串?

  • 回答 (2)
  • 关注 (0)
  • 查看 (1245)

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

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

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

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

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

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

Bilibili科技Bilibili科技提问于
御姐万岁回答于

在Eclipse中,如果你打开选项(在首选项> Java的>编辑>键入)“粘贴到一个字符串时逃生文本”和粘贴多行字符串whithin引号,它会自动添加",并\n" +为您的所有线路。

String str = "paste your text here";
人生的旅途辣鸡前端回答于

这听起来像你想要做一个多线文字,这在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";
Versus 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();
Versus 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.getProperty("line.separator"),也可以使用%n在String.format。

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

扫码关注云+社区

领取腾讯云代金券