Is there an easy way to concatenate several lines of text into a string without constantly appending a newline?(有没有一种简单的方法可以将多行文本连接成一个字符串,而无需不断添加换行符?)
问题描述
所以我基本上需要这样做:
So I essentially need to do this:
String text = "line1
";
text += "line2
";
text += "line3
";
useString( text );
涉及的内容更多,但这是基本思想.有没有什么可以让我在这方面做更多的事情?
There is more involved, but that's the basic idea. Is there anything out there that might let me do something more along the lines of this though?
DesiredStringThinger text = new DesiredStringThinger();
text.append( "line1" );
text.append( "line2" );
text.append( "line3" );
useString( text.toString() );
显然,它不需要完全那样工作,但我想我明白了基本点.总是可以选择编写一个自己处理文本的循环,但是如果有一个标准的 Java 类已经做了这样的事情,而不是我需要在应用程序之间携带一个类,这样我就可以了做些微不足道的事.
Obviously, it does not need to work exactly like that, but I think I get the basic point across. There is always the option of writing a loop which processes the text myself, but it would be nice if there is a standard Java class out there that already does something like this rather than me needing to carry a class around between applications just so I can do something so trivial.
谢谢!
推荐答案
您可以使用 StringWriter
包裹在 PrintWriter
:
You can use a StringWriter
wrapped in a PrintWriter
:
StringWriter stringWriter = new StringWriter();
PrintWriter writer = new PrintWriter(stringWriter, true);
writer.println("line1");
writer.println("line2");
writer.println("line3");
useString(stringWriter.toString());
这篇关于有没有一种简单的方法可以将多行文本连接成一个字符串,而无需不断添加换行符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:有没有一种简单的方法可以将多行文本连接成一个字符串,而无需不断添加换行符?
基础教程推荐
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01