在 C # 中,从字符串中删除换行符最简单的方法是什么?

我希望确保 _ content 不以 NewLine 字符结束:

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

但是,因为 Trim 似乎没有用于字符串集合的重载参数,只有字符。

从字符串的末尾删除 Environment. Newline 最简单的一行程序是什么?

113761 次浏览

关于什么

_content = sb.ToString().Trim(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);
}
_content = sb.TrimEnd(Environment.NewLine.ToCharArray());

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

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

下面这些对我有用。

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

或者

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

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

行被定义为 字符后跟换行符 (“ n”)、回程表(“ r”)或 马车随即返回 通过换行(“ r n”) 返回的 终止回车或终止线 进食。

下面的步骤就可以解决这个问题

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

不如这样:

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

这将从字符串的末尾提取所有空格字符——如果您想保留非换行空格,那么这只是一个问题。

从字符串中删除换行符的最简单方法是首先不要在字符串上使用换行符,确保您自己的代码永远不会看到它。也就是说,通过使用删除换行符的本机函数。如果您逐行要求输出,许多流和 file/io 方法将不包括换行符,尽管可能需要在 System.IO.BufferedStream中包装某些内容。

大多数时候,像 System.IO.File.ReadAllLines这样的东西可以用来代替 System.IO.File.ReadAllText,一旦你使用正确类型的流(例如 BufferedStream) ,就可以用 ReadLine来代替 Read

我不得不删除文本中的所有新行,所以我使用:

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

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

正如马库斯指出的 TrimEnd 现在正在做这项工作。在 Windows Phone 7.8环境中,我需要从字符串的两端获得换行和空白。在尝试了不同的更复杂的选项之后,我的问题通过使用 Trim ()得到了解决——很好地通过了下面的测试

   [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 + "'");
}