将换行符转换为“\n”字符串

Convert newline character to "\n" string

这可能是一个愚蠢的问题,但一些粗略的搜索并没有给我答案。我在寻找字符串中的无效字符时遇到问题;其中恰好是换行符、制表符等。但是,当找到一个时,它会打印到控制台;如您所想,

"Character 
 is invalid"

乍一看可能会混淆团队。那么在 C# 中是否有一种快速简便的方法将换行符转换为其字符串文字版本 "\n",但 不会 转换不是 [=26= 的无效字符]?

这是我的代码的简化版本:

using System.Text.RegularExpressions
class Foo {
    Regex invalidCheck = @"[^\w_ ]";

    public void ParseString(string command) {
        var invalid = invalidCheck.Match(command)
        if (invalid.Success)
            Console.WriteLine("Invalid character " + invalid.Value)
        else {
            // Do things with the string...
        }
    }
}

当程序是运行时,我不知道invalid.Value实际上是什么,但我知道我需要得到它来转换空格字符转换成可读的东西。

I guess you need use this 用“\n”替换“\n”。

喜欢这个。

s = s.Replace("\r", "\"\r\"").Replace("\n", "\"\n\"");

或者您可以创建扩展方法

    public static class MyExtensions
    {
       public static int WordCount(this String str)
       {
           return str.Replace("\r", "\"\r\"").Replace("\n", "\"\n\"");
       }
    }

并调用它并添加尽可能多的无效字符或字符串以根据您的要求进行转换。

您可以使用字典并遍历键值对。

这是一个例子:

String escp(String x) {
    Dictionary<String, String> replacements = new Dictionary<String, String>();
    replacements["\n"] = "\n";
    replacements["\r"] = "\r";
    replacements["\t"] = "\t";
    foreach (var i in replacements) {
       if(x.IndexOf(i.Key) > -1)
          x = x.Replace(i.Key, i.Value);
    }
    return x;
}

你可以这样使用:

String x = "This has\na new line";
Console.WriteLine(x);

String y = escp(x);
Console.WriteLine(y);

对于你的情况,只需用 escp 函数包围 invalid.Value

Console.WriteLine("Invalid character " + escp(invalid.Value));