Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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\n";
text += "line2\n";
text += "line3\n";
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() );

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.

Thanks!

like image 741
Marshmellow1328 Avatar asked Mar 24 '10 15:03

Marshmellow1328


People also ask

What is the most efficient way to concatenate many strings together?

Concat() or + is the best way.

How do I concatenate strings multiple times?

Or you can just take advantage of the fact that multiplying a string concatenates copies of it: add a space to the end of your string and multiply without using join . >>>

Which is the fastest way to concatenate many strings in Java?

concat will typically be the fastest way to concat two String s (but do note null s).


1 Answers

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());
like image 164
Joachim Sauer Avatar answered Oct 12 '22 23:10

Joachim Sauer