Reputation: 8985
I'm getting the text from a TextView
String textString = textView.getText().toString();
The problem is that if the text in the text view has line breaks like this for example
My
Sentence has
line breaks
When I log the text to the console
Log.v("TAG",textString);
Or if I set the text to a TextView
textView.setText(textString);
The result is always displayed with actual line breaks
My
Sentence has
line breaks
And not with the escape characters which is how I want it
My\nSentence has\nline breaks
I know this is a really bad explanation, but how to get the text from the text view with the actual characters that represent the line breaks.
Upvotes: 2
Views: 2775
Reputation: 148
Try this
String demo = edit_new.getText().toString().replace(System.getProperty("line.separator"),"\\n" );
Upvotes: 1
Reputation: 719446
The problem is to format the String that we would represent in Java as
String test = "My\nSentence has\nline breaks";
as follows:
My\nSentence has\nline breaks
i.e. replacing each newline character with a backslash followed by a 'n'
character.
One solution is to use String.replaceAll
. For example, if you know that the line breaks are strictly newline characters then.
String unbroken = broken.replaceAll("\n", "\\\\n");
If the line break could be a platform specific line break then:
String unbroken = broken.replaceAll("\r\n|\n|\r", "\\\\n");
Note that the Java Pattern
will treat a bare CR or NL in the regex as a literal character. However in the replacement string, we need a literal backslash character ... hence it needs to be double-escaped. Another way to write it would be:
String unbroken = broken.replaceAll("\n", Matcher.quoteReplacement("\\n"));
Refer to the javadoc for more details ... and the definitive explanation for the need to handle backslashes as special in the replacement string.
Upvotes: 0