简体   繁体   中英

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

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

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

but the above code doesn't work since Trim seems to not have an overloaded parameter for a collection of strings, only characters.

What is the simplest one-liner to remove an Enivronment.Newline from the end of a string?

The following works for me.

sb.ToString().TrimEnd( '\r', '\n' );

or

sb.ToString().TrimEnd( Environment.NewLine.ToCharArray());

.Trim()为我删除了\\r\\n (使用.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);
}

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.ToString().Trim(Environment.NewLine.ToCharArray());
_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.

How about just:

string text = sb.ToString().TrimEnd(null)

That will pull all whitespace characters from the end of the string -- only a problem if you wanted to preserve non-newline whitespace.

Somewhat of a non-answer, but the easiest way to trim a newline off of a string is to not have the newline on the string in the first place, by making sure it is is never seen by your own code. That is, by using native functions which remove the newline. Many stream and file/io methods will not include the newline if you ask for output line by line, though it may be necessary to wrap something in a System.IO.BufferedStream .

Things like System.IO.File.ReadAllLines can be used in place of System.IO.File.ReadAllText most of the time, and ReadLine can be used instead of Read once you are working with the right type of stream (eg BufferedStream ).

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

I had to remove the new lines all over the text. So I used:

            while (text.Contains(Environment.NewLine))
            {
                text = text.Substring(0, text.Length - Environment.NewLine.Length);
            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM