java 字符串 多行_Java多行字符串

本文对比了在Java中使用StringBuilder、String.format和String.join进行字符串拼接的效率与适用场景,探讨了不同方法的优缺点,以及在处理大字符串和换行符时的解决方案,适合理解字符串操作优化。
摘要由CSDN通过智能技术生成

小编典典

最好的选择是将字符串+组合在一起。人们提到的其他一些选项(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("%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.lineSeparator(),也可以%n在中使用String.format。

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

2020-03-05

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值