2017-09-15 196 views
0

我正在寻找Java SE库或一些常用的函数(例如apache-commons),它们已经提供了以下实现:如何将具有特殊字符的字符串转换为转义字符串的另一个字符串

说,我有不可打印和特殊字符的字符串,如制表符...我想能够获得告诉读者该字符串的实际组成这样的字符串的表示:

举例:

String input = "hello\tworld!!!"; 
System.out.println(input); \\ output looks like: hello world!!! 
String output = printable(input); 
System.out.println(output); \\ output looks like: hello\tworld!!! 
          \\ or 
          \\ output looks like: hello<TAB>world!!! 
          \\ or 
          \\ output looks like: hello\011world!!! 

确切的形式并不重要,但它应该足够好,以便以明确的方式以及程序员可以理解的方式显示字符串内容 。

我可以编码我自己的解决方案,但我想知道是否有一些已经存在的东西。

+1

确实似乎是重复的。然而,我感到惊讶的是,如果不需要转义,只有一个建议的解决方案实际返回传入的相同字符串。而该解决方案甚至没有正确解决问题。 –

回答

1

你可能想看看org.apache.commons.lang3.StringEscapeUtils。它在Apache commons-lang3中可用。

String input = "hello\tworld!!!"; 
System.out.println(input); //output looks like: hello world!!! 
String output = StringEscapeUtils.escapeJava(input); 
System.out.println(output);//output looks like: hello\tworld!!! 
相关问题