How to Print Escape Characters in Java

How do I print escape characters in Java?

One way to do this is:

public static String unEscapeString(String s){
StringBuilder sb = new StringBuilder();
for (int i=0; i<s.length(); i++)
switch (s.charAt(i)){
case '\n': sb.append("\\n"); break;
case '\t': sb.append("\\t"); break;
// ... rest of escape characters
default: sb.append(s.charAt(i));
}
return sb.toString();
}

and you run System.out.print(unEscapeString(x)).

Print String with escape non printable characters

Use Integer.toHexString((int)x.charAt(34));, you can get the string of the unicode char, and add \\u before it, you will get the String.

public static String removeUnicode(String input){
StringBuffer buffer = new StringBuffer(input.length());
for (int i =0; i < input.length(); i++){
if ((int)input.charAt(i) > 256){
buffer.append("\\u").append(Integer.toHexString((int)input.charAt(i)));
} else {
if ( input.charAt(i) == '\n'){
buffer.append("\\n");
} else {
buffer.append(input.charAt(i));
}
}
}
return buffer.toString();
}

Print escaped representation of a String

I think you are looking for:

String xy = org.apache.commons.lang.StringEscapeUtils.escapeJava(yourString);
System.out.println(xy);

from Apache Commons Lang v2.6

deprecated in Apache Commons Lang v3.5+, use Apache Commons Text v1.2

How do i print escape characters as characters?

Escape the slashes (use " \\a") so they won't get interpreted specially. Also you might want to use a lookup table or a switch at least.

switch (c) {
case '\0':
printf(" \\0");
break;
case '\a':
printf(" \\a");
break;
/* And so on. */
}

Printing ALL characters(including escape sequence) of a string

If you open it in text mode, it will treat \r\n as \n, which is why you don't see the \r anywhere. If you want to see the \r, try opening it in binary mode. and doing the same thing, you should see \r as well as \n, unlike when you open the file in text mode.

EDIT:

to open for reading in text mode: fopen(filename, "r").

to open for reading in binary mode: fopen(filename, "rb").



Related Topics



Leave a reply



Submit