对于那些熟悉 Perl 的人来说,“here-document”是一个在其中创建多行字符串的有用工具。源代码。然而,在 Java 中,在每行上使用引号和加号手动连接字符串可能会非常乏味且麻烦。
虽然 Java 中没有与“here-document”语法直接等效的语法,但有几种替代方法考虑有效地创建多行字符串。
1.使用加号运算符 ( ) 连接字符串
最简单的方法是使用加号运算符 ( ) 手动连接字符串。这涉及使用字符串文字 ""n"" 根据需要显式添加换行符:
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";
2。 StringBuilder.append()
StringBuilder 类提供了一个名为append() 的方法,可用于将字符串或其他数据附加到字符串生成器。虽然此技术可能看起来不如使用加号运算符简洁,但它提供了某些优点,例如增强的性能和线程安全性。
StringBuilder sb = new StringBuilder(); sb.append("It was the best of times, it was the worst of times"); sb.append("it was the age of wisdom, it was the age of foolishness"); // ... String s = sb.toString();
3. String.join()
在 Java 8 中引入,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" // ... );
4。 String.format()
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" // ... );
5。存储在文本文件中
对于特别大的字符串,将内容存储在单独的文本文件中,然后将文件的内容读入字符串中可能会很有帮助。这种方法可以帮助避免带有大字符串文字的类文件膨胀。
以上是如何在Java中高效创建多行字符串?的详细内容。更多信息请关注PHP中文网其他相关文章!