user1448108
user1448108

Reputation: 487

How to replace new line characters with actual new lines in a string in android?

I need to display a string which contains a lot of new line '\n'.These needs to be replaced with actual newlines in that string. How can I do that in android?

Upvotes: 1

Views: 6849

Answers (4)

Akshatha S R
Akshatha S R

Reputation: 1345

You can use this..

StringWriter stringWriter = new StringWriter();
PrintWriter writer = new PrintWriter(stringWriter, true);
writer.println("line1");
writer.println("line2");
writer.println("line3");
useString(stringWriter.toString());

line1, line2 and line3 will be printed in separate lines.

Upvotes: 1

3Doubloons
3Doubloons

Reputation: 2106

What seems to be happening is the string you receive from your database contains not the new line character, but rather the characters \ and n. The simplest fix is use simply the String.replace function to replace the character sequence \ n by the character \n like so:

String str = getStringWithFakeNewlines();
str.replace("\\n", "\n"); // The first backslash is doubled to find actual backslashes

Upvotes: 0

JRowan
JRowan

Reputation: 7114

you should concatenate the newline operator like:

String str = "This is testing" + "\n" + "How are you?";

you said from database you could split like:

String[] separated = str.split("\n");
separated[0]; // this will contain "This is testing"
separated[1]; // this will contain "How are you?"

and then concatenate them

Upvotes: 0

hamish
hamish

Reputation: 1182

String myString = "lots of \n new \n lines";
String newStringWithoutNewLines = myString.replace("\n", "");

Upvotes: 0

Related Questions