String.将 CRLF 替换为 '\n'

发布于 2025-01-08 07:19:06 字数 47 浏览 2 评论 0原文

我想知道是否有一种方法可以用 '\n' 替换所有 CRLF 实例。有办法实现吗?

I was wondering if there is a way to replace all instances of CRLF with '\n'. Is there a way to accomplish that?

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

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

发布评论

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

评论(3

对风讲故事 2025-01-15 07:19:06

你尝试过哪些方法不起作用? CRLF 表示回车行饲料。回车符为 \r,换行符为 \n,因此用换行符替换 CRLF 将是

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

这就像任何其他字符串替换一样。需要注意的是 Replace 是一个返回新字符串的方法,因此您需要将结果分配回某个变量,在大多数情况下,它可能与您已经使用的变量名称相同。

编辑:根据下面的评论,您可能会根据 Notepad++ 的行尾转换设置将 CRLF 误认为 LF。在十六进制编辑器中打开文件,看看里面到底有什么。您将看到 CRLF 为 0D 0A(因此回车符为 0D,换行符为 0A)。
Notepad++ 将向您显示您想看到的内容。单击 Edit > 检查行尾转换EOL 转换 > UNIX 格式,即使存在 CRLF,它也会显示 LF 而不是 CRLF。

What have you tried that is not working? CRLF means carriage return, line feed. Carriage return is \r, line feed is \n so replacing CRLF with line feed would be

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

This is just like any other string replace. It is important to note that Replace is 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.

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 editor to see what is really there. You will see CRLF as 0D 0A (so carriage return is 0D and 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 Format and it will show LF instead of CRLF, even if a CRLF is there.

盛装女皇 2025-01-15 07:19:06

如果您确实想用显式字符串“\n”替换回车/换行对,则需要转义反斜杠:

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

If you really want to replace a carriage return/linefeed pair with the explicit string "\n" you need to escape the backslash:

value = value.Replace("\r\n", "\\n"); 
漫雪独思 2025-01-15 07:19:06

我认为看起来我一直在尝试以错误的方向进行替换。

String.Replace('\n', '\r') 

VS

String.Replace('\r', '\n')

似乎现在一切正常。

I think it looks like I have been attempting to replace in the wrong direction.

String.Replace('\n', '\r') 

VS

String.Replace('\r', '\n')

Seem's as though everything is working now.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文