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

后端 未结 10 1442
无人及你
无人及你 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:40

    The following works for me.

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

    or

    sb.ToString().TrimEnd( Environment.NewLine.ToCharArray());
    
    0 讨论(0)
  • 2020-12-13 03:43

    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);
                }
    
    0 讨论(0)
  • 2020-12-13 03:45

    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.

    0 讨论(0)
  • 2020-12-13 03:47

    What about

    _content = sb.ToString().Trim(Environment.NewLine.ToCharArray());
    
    0 讨论(0)
  • 2020-12-13 03:49

    .Trim() removes \r\n for me (using .NET 4.0).

    0 讨论(0)
  • 2020-12-13 03:49

    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 (e.g. BufferedStream).

    0 讨论(0)
提交回复
热议问题