如何在Java中打印转义字符? [英] How do I print escape characters in Java?

查看:700
本文介绍了如何在Java中打印转义字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我有一个字符串时,例如:

When I have a string such as:

String x = "hello\nworld";

使用System.out时,如何让Java打印实际的转义字符(而不将其解释为转义字符)?

How do I get Java to print the actual escape character (and not interpret it as an escape character) when using System.out?

例如,打电话时

System.out.print(x);

我想看看:

hello\nworld

不是:

hello
world

我想查看实际的转义字符以进行调试.

I would like to see the actual escape characters for debugging purposes.

推荐答案

一种方法是:

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();
}

,然后运行System.out.print(unEscapeString(x)).

这篇关于如何在Java中打印转义字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆