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
Cannot Find Firefox Binary in Path. Make Sure Firefox Is Installed
Java Reflection: How to Get the All Getter Methods of a Java Class and Invoke Them
Java Regex: Repeating Capturing Groups
How Does the Java Cast Operator Work
How to Get Backspace \B to Work in Eclipse's Console
Java Thread Priority Has No Effect
How to Determine If a List Is Sorted in Java
Convert a Date Format in Epoch
What's the Point of Guava's Optional Class
How to Fix "Unsupported Class File Major Version 60" in Intellij Idea
How Does Memory Reordering Help Processors and Compilers
Javamail API to Imail -- Java.Net.Socketexception: Permission Denied: Connect
How to Automate Drag & Drop Functionality Using Selenium Webdriver Java
Simpledateformat Parse(String Str) Doesn't Throw an Exception When Str = 2011/12/12Aaaaaaaaa