What is the easiest way in C# to trim a newline off of a string?

后端 未结 10 1530
无人及你
无人及你 2020-12-13 03:11

I want to make sure that _content does not end with a NewLine character:

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

10条回答
  •  长情又很酷
    2020-12-13 04:00

    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);
    }
    

提交回复
热议问题