Himanshu Aggarwal
Himanshu Aggarwal

Reputation: 1809

Can a string be converted to a string containing escape sequences in Java?

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

Answers (2)

Nick
Nick

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

Konstantin Yovkov
Konstantin Yovkov

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

Related Questions