什么是在C#中修剪一个string的换行最简单的方法?

我想确保_content不以NewLine字符结尾:

_content = sb.ToString().Trim(new char[] { Environment.NewLine }); 

上面的代码不起作用,因为Trim似乎没有一个string集合的重载参数,只有字符。

什么是从string的末尾删除Enivronment.Newline的最简单的单行程?

以下为我工作。

 sb.ToString().TrimEnd( '\r', '\n' ); 

要么

 sb.ToString().TrimEnd( Environment.NewLine.ToCharArray()); 

怎么样:

 public static string TrimNewLines(string text) { while (text.EndsWith(Environment.NewLine)) { text = text.Substring(0, text.Length - Environment.NewLine.Length); } return text; } 

如果有多个换行符,效率会比较低,但是会起作用。

或者,如果您不介意修剪(比如说) "\r\r\r\r""\n\n\n\n"而不是"\r\n\r\n\r\n"

 // No need to create a new array each time private static readonly char[] NewLineChars = Environment.NewLine.ToCharArray(); public static string TrimNewLines(string text) { return text.TrimEnd(NewLineChars); } 

.Trim()为我删除\r\n (使用.NET 4.0)。

使用框架。 ReadLine()方法具有以下内容:

一行被定义为一个字符序列,后跟一个换行符(“\ n”),一个回车符(“\ r”)或一个回车符后跟一个换行符(“\ r \ n”)。 返回的string不包含终止回车或换行符。

所以下面的就是这个诀窍

 _content = new StringReader(sb.ToString()).ReadLine(); 

关于什么

 _content = sb.ToString().Trim(Environment.NewLine.ToCharArray()); 
 _content = sb.TrimEnd(Environment.NewLine.ToCharArray()); 

这当然会删除“\ r \ r \ r \ r”以及“\ n \ n \ n \ n”等组合。 在NewLine不是“\ n \ r”的“环境”中,您可能会遇到一些奇怪的行为:-)

但是,如果你能忍受这一点,那么我相信这是删除一个string末尾的新行字符的最有效的方法。

如何只是:

 string text = sb.ToString().TrimEnd(null) 

这将从string的末尾拉出所有空白字符 – 如果您想保留非换行符空白,则只是一个问题。

有些是没有答案的,但是从string中删除换行符的最简单方法是首先不要在string上换行,通过确保它是从未被自己的代码看到的。 也就是说,通过使用删除换行符的本地函数。 许多stream和文件/ io方法将不会包含换行符,如果您逐行询问输出,虽然可能需要将某些内容包装在System.IO.BufferedStream

System.IO.File.ReadAllLines这样的东西大部分时间都可以用来代替System.IO.File.ReadAllText ,一旦你使用了正确types的stream(例如BufferedStream ),就可以使用ReadLine来代替Read

我不得不在整个文本中删除新的行。 所以我用:

  while (text.Contains(Environment.NewLine)) { text = text.Substring(0, text.Length - Environment.NewLine.Length); } 

正如Markus指出TrimEnd现在正在做这项工作。 我需要在Windows Phone 7.8环境中从string的两端获得换行符和空格。 在追逐了不同更复杂的选项之后,我的问题只能通过使用Trim()来解决 – 很好地传递了下面的testing

  [TestMethod] [Description("TrimNewLines tests")] public void Test_TrimNewLines() { Test_TrimNewLines_runTest("\n\r testi \n\r", "testi"); Test_TrimNewLines_runTest("\r testi \r", "testi"); Test_TrimNewLines_runTest("\n testi \n", "testi"); Test_TrimNewLines_runTest("\r\r\r\r\n\r testi \r\r\r\r \n\r", "testi"); Test_TrimNewLines_runTest("\n\r \n\n\n\n testi äål., \n\r", "testi äål.,"); Test_TrimNewLines_runTest("\n\n\n\n testi ja testi \n\r\n\n\n\n", "testi ja testi"); Test_TrimNewLines_runTest("", ""); Test_TrimNewLines_runTest("\n\r\n\n\r\n", ""); Test_TrimNewLines_runTest("\n\r \n\n \n\n", ""); } private static void Test_TrimNewLines_runTest(string _before, string _expected) { string _response = _before.Trim(); Assert.IsTrue(_expected == _response, "string '" + _before + "' was translated to '" + _response + "' - should have been '" + _expected + "'"); }