从 C# 中的字符串中删除换行符的最快方法是什么?

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

What would be the fastest way to remove Newlines from a String in C#?

提问by Martin Marconcini

I have a string that has some Environment.Newline in it. I'd like to strip those from the string and instead, replace the Newline with something like a comma.

我有一个字符串,其中包含一些 Environment.Newline。我想从字符串中删除它们,而是用逗号之类的东西替换换行符。

What would be, in your opinion, the best way to do this using C#.NET 2.0?

在您看来,使用 C#.NET 2.0 执行此操作的最佳方法是什么?

采纳答案by mmattax

Why not:

为什么不:

string s = "foobar\ngork";
string v = s.Replace(Environment.NewLine,",");
System.Console.WriteLine(v);

回答by Konrad Rudolph

The best way is the builtin way: Use string.Replace. Why do you need alternatives?

最好的方式是内置方式:使用string.Replace. 为什么需要替代品?

回答by Bjorn Reppen

string sample = "abc" + Environment.NewLine + "def";
string replaced = sample.Replace(Environment.NewLine, ",");

回答by Fredrik Kalseth

Don't reinvent the wheel — just use:

不要重新发明轮子 - 只需使用:

myString.Replace(Environment.NewLine, ",")

回答by Steve

Like this:

像这样:

string s = "hello\nworld";
s = s.Replace(Environment.NewLine, ",");