最好的选择是将字符串
+组合在一起。人们提到的其他一些选项(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。
另一个选择是将资源放在文本文件中,然后仅读取该文件的内容。对于非常大的字符串,这将是更好的选择,以避免不必要地使您的类文件膨胀。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)