C# String.Replace CRLF 为 '\n'
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9400959/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
String.Replace CRLF with '\n'
提问by SoftwareSavant
I was wondering if there is a way to replace all instances of CRLF with '\n'. Is there a way to accomplish that?
我想知道是否有办法用 '\n' 替换 CRLF 的所有实例。有没有办法做到这一点?
采纳答案by SoftwareSavant
I think it looks like I have been attempting to replace in the wrong direction.
我认为看起来我一直试图在错误的方向上进行替换。
String.Replace('\n', '\r')
VS
VS
String.Replace('\r', '\n')
Seem's as though everything is working now.
好像现在一切正常。
回答by Bob
What have you tried that is not working? CRLF means carriage return, line feed. Carriage return is \r, line feed is \nso replacing CRLF with line feed would be
你试过什么不起作用?CRLF 表示回车、换行。回车是\r换行,\n所以用换行替换 CRLF 将是
value = value.Replace("\r\n", "\n");
This is just like any other string replace. It is important to note that Replaceis a method which returns a new string, so you need to assign the result back to some variable, in most cases it will probably be the same variable name you were already using.
这就像任何其他字符串替换一样。重要的是要注意Replace是一种返回新字符串的方法,因此您需要将结果分配回某个变量,在大多数情况下,它可能与您已经使用的变量名称相同。
Edit: based on your comment below, you are probably mistaking CRLF for LF based on Notepad++'s end of line conversion setting. Open your file in a hex editorto see what is really there. You will see CRLF as 0D 0A(so carriage return is 0Dand line feed is 0A).
Notepad++ will show you what you want to see. Checked your end of line conversion by clicking Edit > EOL Conversion > UNIX Formatand it will show LF instead of CRLF, even if a CRLF is there.
编辑:根据您在下面的评论,您可能会根据 Notepad++ 的行尾转换设置将 CRLF 误认为 LF。在十六进制编辑器中打开您的文件以查看真正存在的内容。你会看到 CRLF 为0D 0A(所以回车是0D,换行是0A)。Notepad++ 将显示您想看到的内容。通过单击检查您的行尾转换Edit > EOL Conversion > UNIX Format,即使存在 CRLF,它也会显示 LF 而不是 CRLF。
回答by HABO
If you really want to replace a carriage return/linefeed pair with the explicit string "\n" you need to escape the backslash:
如果你真的想用显式字符串“\n”替换回车/换行对,你需要转义反斜杠:
value = value.Replace("\r\n", "\n");

