I want to make sure that _content does not end with a NewLine character:
_content = sb.ToString().Trim(new char[] { Environment.NewLine });
As Markus pointed out TrimEnd is doing the job now. I needed to get line feeds and white space from both ends of string in Windows Phone 7.8 environment. After having chased different more complex options my problem was solved by using Trim() only - passed the following tests nicely
[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 + "'");
}
How about:
public static string TrimNewLines(string text)
{
while (text.EndsWith(Environment.NewLine))
{
text = text.Substring(0, text.Length - Environment.NewLine.Length);
}
return text;
}
It's somewhat inefficient if there are multiple newlines, but it'll work.
Alternatively, if you don't mind it trimming (say) "\r\r\r\r"
or "\n\n\n\n"
rather than just "\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);
}
Use the Framework. The ReadLine() method has the following to say:
A line is defined as a sequence of characters followed by a line feed ("\n"), a carriage return ("\r") or a carriage return immediately followed by a line feed ("\r\n"). The string that is returned does not contain the terminating carriage return or line feed.
So the following will do the trick
_content = new StringReader(sb.ToString()).ReadLine();
_content = sb.TrimEnd(Environment.NewLine.ToCharArray());
This will of course remove "\r\r\r\r" as well as "\n\n\n\n" and other combinations. And in "enviroments" where NewLine is other than "\n\r" you might get some strange behaviors :-)
But if you can live with this then I belive this is the most effectiv way to remove new line characters at the end of a string.