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

后端 未结 10 1507
无人及你
无人及你 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 03:54

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

提交回复
热议问题