Domanda

Let say I have

String str="hello\" world\\";

when printing str, the output is

hello" world\

even when printing str.length() the output is

13

Is there any way to prove that str value has escape character(s)?

È stato utile?

Soluzione

There is no such thing as escape characters at run time.

Escape characters appear only in String literals. For example,

String literal = "Some\nEscape\rSequence\\\"";

At compilation time, the compiler produces a String value with their actual binary representation (UTF-8 iirc). The JVM uses that String value directly.

You wrote

I am thinking that whenever we print a string and the output contains character such as " and \, then we can conclude that those character, " and \ was escaped?

This is not true, those characters might have been read from a file or some other InputStream. They were definitely not escaped in a text file.

Altri suggerimenti

Yes.

Use the Apache Commons Library, specifically StringEscapeUtils#escapeJava.

jshell> StringEscapeUtils.escapeJava("Newline \n here \u0344 and unicode \f\n\r\t\"\0\13 and more")
$136 ==> "Newline \\n here \\u0344 and unicode \\f\\n\\r\\t\\\"\\u0000\\u000B and more"

This prepends a backslash to each escape sequence and also swaps the variable-width octal sequences for fixed-width Unicode sequences. This means that every escape sequence will consist of "\\" two backslashes, followed by one of {n, b, r, t, f, ", \}, or a 'u' character, plus exactly four hexadecimal [0-F] digits.

If you just want to know whether or not the original String contains escape sequences, search for "\\" in the Apache-fied string. If you want to find the positions of those sequences, it's a bit more involved.

See more at this Gist.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top