代码之家  ›  专栏  ›  技术社区  ›  Valentin Ruano

如何将具有特殊字符的字符串转换为另一个字符串,并在其中转义[重复]

  •  0
  • Valentin Ruano  · 技术社区  · 9 年前

    比如,我有一个字符串,带有不可打印的特殊字符,例如制表符。。。我希望能够获得这样一个字符串的表示,告诉读者字符串的实际组成:

    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 回复  |  直到 9 年前
        1
  •  1
  •   dpr    9 年前

    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!!!