如何强制 Console.WriteLine() 逐字打印字符串?

发布于 2025-01-08 18:03:15 字数 695 浏览 0 评论 0原文

可能的重复:
我可以将 C# 字符串值转换为转义字符串文字

如何打印字符串(通过 Console.WriteLine()),以便逐字打印字符串中可能存在的任何/所有转义序列?

示例:

string s = "This \r\n has \t special \\ characters.";
Console.WriteLine(s);

/* Output (I don't want this)

This 
 has    special \ characters.

*/

我希望输出为:

This \r\n has \t special \\ characters.

请注意,在我的应用程序中,我从第三方接收字符串(其中包含转义序列) - 即,如果我自己创建字符串,我知道我可以这样做

string s = @"This \r\n has \t special \\ characters.";

Possible Duplicate:
Can I convert a C# string value to an escaped string literal

How can I print a string (via Console.WriteLine()) such that any/all escape sequences that may exist in the string is printed verbatim?

Example:

string s = "This \r\n has \t special \\ characters.";
Console.WriteLine(s);

/* Output (I don't want this)

This 
 has    special \ characters.

*/

I want the output to read:

This \r\n has \t special \\ characters.

Note that in my application I am receiving the string (which contains the escape sequences) from a third party - i.e. If I were creating the string myself, I'm aware that I could just do

string s = @"This \r\n has \t special \\ characters.";

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

泪之魂 2025-01-15 18:03:15

做到这一点的唯一方法是自己解码转义序列并将它们作为文字条目放回到字符串中。这将需要某种转换功能。例如

string EscapeIt(string value) {
  var builder = new StringBuilder();
  foreach (var cur in value) {
    switch (cur) {
      case '\t': 
        builder.Append(@"\t");
        break;
      case '\r': 
        builder.Append(@"\r");
        break;
      case '\n':
        builder.Append(@"\n");
        break;
      // etc ...
      default:
        builder.Append(cur);
        break;
    }
  }
  return builder.ToString();
}

The only way to do this is to decode the escape sequences yourself and put them back as literal entries into the string. This would require some sort of conversion function. For example

string EscapeIt(string value) {
  var builder = new StringBuilder();
  foreach (var cur in value) {
    switch (cur) {
      case '\t': 
        builder.Append(@"\t");
        break;
      case '\r': 
        builder.Append(@"\r");
        break;
      case '\n':
        builder.Append(@"\n");
        break;
      // etc ...
      default:
        builder.Append(cur);
        break;
    }
  }
  return builder.ToString();
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文