来自Perl,我肯定错过了在源代码中创建多行字符串的“here-document”方法:
$string = <<"EOF" # create a three-line string
text
text
text
EOF
在Java中,当我从头开始连接多行字符串时,我必须在每一行上使用繁琐的引号和加号。
有什么更好的选择吗?在属性文件中定义我的字符串?
编辑:有两个答案说StringBuilder.append()比加号更可取。谁能详细解释一下他们为什么这么想?在我看来,这一点也不可取。我正在寻找一种方法来解决多行字符串不是一级语言结构这一事实,这意味着我绝对不想用方法调用取代一级语言结构(字符串连接与加号)。
编辑:为了进一步澄清我的问题,我根本不关心性能。我关心的是可维护性和设计问题。
从问题中还不完全清楚作者是否有兴趣处理某种需要有一些动态值的格式化大字符串,但如果是这种情况,像StringTemplate (http://www.stringtemplate.org/)这样的模板引擎可能非常有用。
下面是一个使用StringTemplate的简单代码示例。实际的模板("Hello, < name >")可以从外部纯文本文件加载。模板中的所有缩进都将被保留,不需要转义。
import org.stringtemplate.v4.*;
public class Hello {
public static void main(String[] args) {
ST hello = new ST("Hello, <name>");
hello.add("name", "World");
System.out.println(hello.render());
}
}
附注:为了可读性和本地化目的,从源代码中删除大块文本总是一个好主意。
从问题中还不完全清楚作者是否有兴趣处理某种需要有一些动态值的格式化大字符串,但如果是这种情况,像StringTemplate (http://www.stringtemplate.org/)这样的模板引擎可能非常有用。
下面是一个使用StringTemplate的简单代码示例。实际的模板("Hello, < name >")可以从外部纯文本文件加载。模板中的所有缩进都将被保留,不需要转义。
import org.stringtemplate.v4.*;
public class Hello {
public static void main(String[] args) {
ST hello = new ST("Hello, <name>");
hello.add("name", "World");
System.out.println(hello.render());
}
}
附注:为了可读性和本地化目的,从源代码中删除大块文本总是一个好主意。