Answers:
以下对我有用。
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);
}
使用框架。ReadLine()方法具有以下含义:
一行定义为一个字符序列,后跟换行符(“ \ n”),回车符(“ \ r”)或回车符后紧跟换行符(“ \ r \ n”)。返回的字符串不包含回车符或换行符。
因此,以下将解决问题的技巧
_content = new StringReader(sb.ToString()).ReadLine();
关于什么
_content = sb.ToString().Trim(Environment.NewLine.ToCharArray());
正如Markus指出的那样,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 + "'");
}
我必须删除整个文本中的新行。所以我用了:
while (text.Contains(Environment.NewLine))
{
text = text.Substring(0, text.Length - Environment.NewLine.Length);
}