How do I escape a string in Java?

Solution 1:

You should use the StringEscapeUtils class from Apache Commons Text (you can also find the class in Apache Commons Lang3 but that one is deprecated). You'll find that there are plenty of other offerings in Apache Commons that might serve useful for other problems you have in Java development, so that you don't reinvent the wheel.

The specific call you want has to do with "Java escaping"; the API call is StringEscapeUtils.escapeJava(). For example:

System.out.println(StringEscapeUtils.escapeJava("Hello\r\n\tW\"o\"rld\n"));

would print out:

Hello\r\n\tW\"o\"rld\n

There are plenty of other escaping utilities in that library as well. You can find Apache Commons Text in Maven Central and you'd add it to your Maven project like this:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-text</artifactId>
    <version>1.3</version>
</dependency>

and in case you are using Gradle:

compile "org.apache.commons:commons-text:1.3"

Solution 2:

Many of the solutions here suggest adding the Apache Commons Text and using StringEscapeUtils. Some of the other solutions here are simply wrong.

A potential solutions is as follows:

/**
 * escape()
 *
 * Escape a give String to make it safe to be printed or stored.
 *
 * @param s The input String.
 * @return The output String.
 **/
public static String escape(String s){
  return s.replace("\\", "\\\\")
          .replace("\t", "\\t")
          .replace("\b", "\\b")
          .replace("\n", "\\n")
          .replace("\r", "\\r")
          .replace("\f", "\\f")
          .replace("\'", "\\'")
          .replace("\"", "\\\"");
}

The escape list is from Oracle's list. (Note that \\ is escaped first as you don't want to re-escape it later.)

This solution isn't as fast as it could be, but it should work. Ideally you would only parse the String once and you wouldn't need to keep rebuilding your String array. For small Strings this should be fine.

If you're thinking about this from the perspective of storing data, also consider something like converting it to Base64 representation - it's fast, single parse and uses not too much extra space.

Solution 3:

Using:

\\n and \\t

Some characters preceded by a backslash (\) form an escape sequence and have special meaning to the compiler. So in your case \n and \t are treated as special (newline and tab respectively). So we need to escape the backslash to make n and t treated literally.

Solution 4:

StringEscapeUtils is good for string related operations