在C#中,替换字符中的回车换行,在这之前 我们需要知道的一个小常识:
| 名称 | 英文 | 描述 | ASCII 值 | C# 表示 |
|---|---|---|---|---|
| 回车符 | Carriage Return | 回到一行开头 | 13 | \r |
| 换行符 | New Line | 下一行开头位置 | 10 | \n |
代码示例如下:
//Assert.Pass();
string s = "我是测试文字,在这里测试回车换行\r\n这里第二行的开始\n https://lebang2020.cn";
string s1 = s.Replace("\r\n", string.Empty).Replace("\n", string.Empty);
string s2 = s.Replace(Convert.ToChar(10).ToString(), string.Empty)
.Replace(Convert.ToChar(13).ToString(), string.Empty);
string s3 = Regex.Replace(s, Environment.NewLine, string.Empty);
string s4 = Regex.Replace(s3, "\\n", string.Empty);
Regex regex1 = new Regex("\r\n");
string s5 = regex1.Replace(s, string.Empty);
Regex regex2 = new Regex("\n");
string s6 = regex2.Replace(s5, string.Empty);
其中 Environment.NewLine 需要我们注意一下,它在windows下代表的是 "\r\n",不同的系统代表的值可能不同。
正常字符中我们可能会遇到“\r\n” 或者"\n" ,所以都要分别做处理才行。