Reputation: 1809
Say I enter a string:-
Hello
Java!
I want the output as:-
Hello\nJava!
Is there any way in which I could get the output in this format?
I am stuck on this one and not able to think about any logic which could do this for me.
Upvotes: 0
Views: 54
Reputation: 607
It looks like http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringEscapeUtils.html does what you want.
EG
String escaped = StringEscapeUtils.escapeJava(String str)
Will return "Hello\nJava!" when supplied with your string.
Upvotes: 2
Reputation: 62864
Hm..You can replace the new line character(\n
) with \\n
. For example:
String helloWithNewLine = "Hello\nJava";
String helloWithoutNewLine = helloWithNewLine.replace("\n", "\\n");
System.out.println(helloWithoutNewLine);
Output:
Hello\nJava
Upvotes: 1