c#字符串中的换行符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14214828/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 11:05:20  来源:igfitidea点击:

newline character in c# string

c#stringnewline

提问by peter

I have some html code in a C# string. If I look with the Text Visualizer of Visual Studio I can see it has numerous newlines in it. However, after i apply this code

我在 C# 字符串中有一些 html 代码。如果我使用 Visual Studio 的 Text Visualizer 进行查看,我可以看到其中有许多换行符。但是,在我应用此代码后

string modifiedString = originalString.Replace(Environment.NewLine, "<br />");

and then I look with the Text Visualizer at modifiedString I can see it doesn't have anymore newlines except for 3 places. Are there any other character types than resemble newline and I am missing?

然后我用文本可视化器查看 modifiedString 我可以看到它除了 3 个地方外不再有换行符。除了类似换行符之外,还有其他字符类型吗?我失踪了吗?

采纳答案by juharr

They might be just a \ror a \n. I just checked and the text visualizer in VS 2010 displays both as newlines as well as \r\n.

它们可能只是一个\r或一个\n。我刚刚检查过,VS 2010 中的文本可视化器同时显示为换行符和\r\n.

This string

这个字符串

string test = "blah\r\nblah\rblah\nblah";

Shows up as

显示为

blah
blah
blah
blah

in the text visualizer.

在文本可视化工具中。

So you could try

所以你可以试试

string modifiedString = originalString
    .Replace(Environment.NewLine, "<br />")
    .Replace("\r", "<br />")
    .Replace("\n", "<br />");

回答by Mick Bruno

A great way of handling this is with regular expressions.

处理这个问题的一个好方法是使用正则表达式。

string modifiedString = Regex.Replace(originalString, @"(\r\n)|\n|\r", "<br/>");


This will replace any of the 3 legal types of newline with the html tag.


这将用 html 标记替换 3 种合法类型的换行符中的任何一种。