【问题标题】:How can I translate a string with special character into another string where these are escaped [duplicate]如何将具有特殊字符的字符串翻译成另一个字符串,这些字符串被转义[重复]
【发布时间】:2018-02-24 22:28:42
【问题描述】:

我正在寻找 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!!!

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

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

【问题讨论】:

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

标签: java string unicode char escaping


【解决方案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!!!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-14
    • 2019-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-11
    相关资源
    最近更新 更多