C# 如何从该字符串中删除换行符?
我花了很多很多时间寻找答案。如果你在这个网站上查找“删除新行”,它给出的答案看起来是可行的,但我无法让它们起作用C# 如何从该字符串中删除换行符?,c#,newline,C#,Newline,我花了很多很多时间寻找答案。如果你在这个网站上查找“删除新行”,它给出的答案看起来是可行的,但我无法让它们起作用 string TextFileBlock = File.ReadAllText("TextFile.txt"); char newlinechar = '\n' ; TextFileBlock = TextFileBlock.Replace(" ", String.Empty); //works for the spaces TextFileBlock = TextFil
string TextFileBlock = File.ReadAllText("TextFile.txt");
char newlinechar = '\n' ;
TextFileBlock = TextFileBlock.Replace(" ", String.Empty); //works for the spaces
TextFileBlock = TextFileBlock.Replace(newlinechar.ToString(), String.Empty);
///Does not get rid of the newlines. The enter key.
// TextFileBlock = TextFileBlock.Replace("\n", String.Empty);// not works
//TextFileBlock.Replace(Environment.NewLine, string.Empty);//not works
C问题这应该解决:
public static string RemoveNewLines(this string input)
{
return input.Replace("\r\n", string.Empty)
.Replace("\n", string.Empty)
.Replace("\r", string.Empty);
}
假设文件相当小,可以将整个段替换为:
string[] lines = File.ReadAllLines("TextFile.txt");
string TextFileBlock = String.Concat(lines).Replace(" ", "");
该方法返回一个行数组,其中一行由回车符、换行符或CRLF \r\n终止。数组中的单个元素不包括终止回车符或换行符,因此在连接数组元素时不包括在最终字符串中。您知道,在Windows上,新行由回车符和换行符组成\r\n,而不仅仅是\n?如果您对文件中的字符有疑问,请在十六进制编辑器中查看它,例如。根据该逻辑,操作代码应该删除\n并保留\r。最好只返回输入。替换\n,string.Empty。替换\r,string.Empty;因为这两个方法负责\r\n