Java - Replace New Line Character by \N

Replace '\n' by ',' in java

\n is the new line character. If you need to replace that actual backslash character followed by n, Then you need to use this:

String test ="s1\ns2\ns3\ns4";
System.out.println(test.replaceAll("\\n",","));

Update:

You can use the System.lineSeparator(); instead of the \n character.

System.out.println(test.replaceAll(System.lineSeparator(),","));

How do I replace line break with "\n" with java?

If you want the backslash to show up you have to escape it. Otherwise it will be interpreted as a new line.

str = str.replaceAll("\n","\\\\n"));

Find and replace all NewLine or BreakLine characters with \n in a String - Platform independent

If you want literal \n then following should work:

String repl = str.replaceAll("(\\r|\\n|\\r\\n)+", "\\\\n")

Replace new line with n in Java

Try replacing other linebreak symbols : EditText.getText().replaceAll("\r\n|\r", "\n");

java - Replace new line character by \n

You don't need to use replaceAll unless you are trying to use regular expressions. replace works fine.

sourceCode = sourceCode.replace("\n", "\\n");

Why can't I replace \n in a given String?

Strings in Java are immutable and as such the new string with the replacements is stored in newString, not oldString.

EDIT

I see now that your issue was not actually related to Java String immutability but rather the difference between replace() and replaceAll(). The difference between these is that replaceAll() takes in a regex as the first argument, which will then replace any matches with the second argument, whereas replace() simply takes in a CharSequence (of which String is an implementation) and will replace exact matches with the second argument.

In your case, I think your original String had the newline characters escaped:

String str = "Vorgang nicht möglich\\n\\nBitte Karte entnehmen";

which meant that the String didn't actually contain newline characters at all; it contained literally "\n". This would mean that:

str.replaceAll("\\n", " ");

will resolve the first argument to a regex and replace newline characters (of which there were none), and:

str.replace("\\n", " ");

will replace exact matches of "\n". It's also worth noting that as others have pointed out contains() also doesn't take in a regex, which is why running:

oldString.contains("\\n");

returned true.



Related Topics



Leave a reply



Submit