打印带有转义不可打印字符的字符串
我有这个字符串
String x="String containning special chars \u202C \n \u202C \u202C \u202C";
如何打印出来: String containning special chars \u202C \n \u202C \u202C \u202C
?
试着
System.out.println(x.replace("\\","\\\\"));
但是只打印包含String containning special chars \n
也试过了
String out = org.apache.commons.lang3.StringEscapeUtils.unescapeJava(x); System.out.println(out);
但这也无济于事。
任何一个有我不知道的建议或API的人?
更新 – 解决方案
在@lbear aproach之后,我想出了这个函数来处理大多数转义字符串的情况
public static String removeUnicodeAndEscapeChars(String input) { StringBuilder buffer = new StringBuilder(input.length()); for (int i = 0; i 256) { buffer.append("\\u").append(Integer.toHexString((int) input.charAt(i))); } else { if (input.charAt(i) == '\n') { buffer.append("\\n"); } else if(input.charAt(i) == '\t'){ buffer.append("\\t"); }else if(input.charAt(i) == '\r'){ buffer.append("\\r"); }else if(input.charAt(i) == '\b'){ buffer.append("\\b"); }else if(input.charAt(i) == '\f'){ buffer.append("\\f"); }else if(input.charAt(i) == '\''){ buffer.append("\\'"); }else if(input.charAt(i) == '\"'){ buffer.append("\\"); }else if(input.charAt(i) == '\\'){ buffer.append("\\\\"); }else { buffer.append(input.charAt(i)); } } } return buffer.toString(); }
使用Integer.toHexString((int)x.charAt(34));
,你可以获取unicode char的字符串,并在它之前添加\\u
,你将得到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(); }
Apache Commons StringEscapeUtils具有HTML编码。 此编码非常接近您可能需要的
String escaped code = StringEscapeUtils.escapeHtml(rowId)
见文档
String original = "String containning special chars \u202C \n \u202C \u202C \u202C"; String escaped = original.replace("\u202C", "\\u202C"); System.out.println(escaped);
- 如何在Android Studio中修复“组织导入”以进行静态导入
- Android – 获取地图叠加项目的点击事件
- 使用SSL与Bouncy Castle进行Android到服务器通信
- 使用Scanner类输入
- 使用poi-ooxml jar文件创建.docx文件
- AppEnginePlugin:不支持的major.minor版本51.0 – appengine 1.9.17
- 循环AsyncTask类必须声明为abstract或实现抽象方法
- float和double的不同值
- 如何在React Native for Android Apps中设置canOverrideExistingModule = true?