来自Perl,我肯定错过了在源代码中创建多行字符串的“here-document”方法:
$string = <<"EOF" # create a three-line string
text
text
text
EOF
在Java中,当我从头开始连接多行字符串时,我必须在每一行上使用繁琐的引号和加号。
有什么更好的选择吗?在属性文件中定义我的字符串?
编辑:有两个答案说StringBuilder.append()比加号更可取。谁能详细解释一下他们为什么这么想?在我看来,这一点也不可取。我正在寻找一种方法来解决多行字符串不是一级语言结构这一事实,这意味着我绝对不想用方法调用取代一级语言结构(字符串连接与加号)。
编辑:为了进一步澄清我的问题,我根本不关心性能。我关心的是可维护性和设计问题。
加号被转换为StringBuilder。除非两个字符串都是常量,以便编译器可以在编译时将它们组合在一起。至少,Sun的编译器是这样的,我怀疑大多数(如果不是所有)其他编译器也会这样做。
So:
String a="Hello";
String b="Goodbye";
String c=a+b;
通常生成完全相同的代码:
String a="Hello";
String b="Goodbye":
StringBuilder temp=new StringBuilder();
temp.append(a).append(b);
String c=temp.toString();
另一方面:
String c="Hello"+"Goodbye";
等于:
String c="HelloGoodbye";
也就是说,为了可读性,在多行中使用加号将字符串字面量分开并不会受到惩罚。
import org.apache.commons.lang3.StringUtils;
String multiline = StringUtils.join(new String[] {
"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",
}, "\n");
由于Java(还)不支持多行字符串,目前唯一的方法是使用前面提到的技术之一来破解它。我使用上面提到的一些技巧构建了下面的Python脚本:
import sys
import string
import os
print 'new String('
for line in sys.stdin:
one = string.replace(line, '"', '\\"').rstrip(os.linesep)
print ' + "' + one + ' "'
print ')'
把它放在一个名为javastringify.py的文件中,把你的字符串放在一个名为mystring.txt的文件中,然后像下面这样运行:
cat mystring.txt | python javastringify.py
然后,您可以复制输出并将其粘贴到编辑器中。
修改这需要处理任何特殊情况,但这是为我的需要。希望这能有所帮助!