What is the easiest way in C# to trim a newline off of a string?
The following works for me.
sb.ToString().TrimEnd( '\r', '\n' );
or
sb.ToString().TrimEnd( Environment.NewLine.ToCharArray());
.Trim()
removes \r\n
for me (using .NET 4.0).
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);
}