栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Java多行字符串

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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";
     +

对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("%sn%sn%sn%sn%sn%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

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



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/391464.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号