在C#中修剪字符串的换行符最简单的方法是什么?

时间:2022-04-11 14:08:02

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

我想确保_content不以NewLine字符结尾:

_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.

但上面的代码不起作用,因为Trim似乎没有字符串集合的重载参数,只有字符。

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

从字符串末尾删除Enivronment.Newline的最简单的单线程是什么?

10 个解决方案

#1


The following works for me.

以下适用于我。

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

or

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

#2


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

.Trim()为我删除了\ r \ n(使用.NET 4.0)。

#3


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":

或者,如果你不介意它修剪(比如说)“\ r \ n \ r \ r \ n”或“\ n \ n \ n \ n”而不仅仅是“\ r \ n \ r \ n \ n \ n \ 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);
}

#4


Use the Framework. The ReadLine() method has the following to say:

使用框架。 ReadLine()方法有如下说法:

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.

一行被定义为一个字符序列,后跟一个换行符(“\ n”),一个回车符(“\ r”)或一个回车符后面紧跟一个换行符(“\ r \ n”)。返回的字符串不包含终止回车符或换行符。

So the following will do the trick

所以以下方法就可以了

_content = new StringReader(sb.ToString()).ReadLine();

#5


What about

_content = sb.ToString().Trim(Environment.NewLine.ToCharArray());

#6


_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 :-)

这当然会删除“\ r \ n \ r \ n \ r \ n”以及“\ n \ n \ n \ n”和其他组合。在NewLine不是“\ n \ r”的“环境”中你可能会得到一些奇怪的行为:-)

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.

但是如果你能忍受这一点,那么我相信这是在字符串末尾删除新行字符最有效的方法。

#7


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.

这将从字符串的末尾拉出所有空格字符 - 如果您想保留非换行符空格,则只会出现问题。

#8


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.

有点不回答,但是从字符串中修剪换行的最简单方法是首先在字符串上没有换行符,确保它自己的代码永远不会看到它。也就是说,通过使用删除换行符的本机函数。如果逐行请求输出,许多流和文件/ io方法将不包括换行符,尽管可能需要在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).

像System.IO.File.ReadAllLines这样的东西大部分时间都可以代替System.IO.File.ReadAllText使用,一旦你使用正确类型的流(例如BufferedStream),可以使用ReadLine而不是Read。

#9


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

正如马库斯所指出的,TrimEnd现在正在做这项工作。我需要在Windows Phone 7.8环境中从字符串的两端获取换行符和空格。在追逐了不同的更复杂的选项后,我的问题只通过使用Trim()解决了 - 很好地通过了以下测试

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

#10


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

#1


The following works for me.

以下适用于我。

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

or

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

#2


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

.Trim()为我删除了\ r \ n(使用.NET 4.0)。

#3


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":

或者,如果你不介意它修剪(比如说)“\ r \ n \ r \ r \ n”或“\ n \ n \ n \ n”而不仅仅是“\ r \ n \ r \ n \ n \ n \ 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);
}

#4


Use the Framework. The ReadLine() method has the following to say:

使用框架。 ReadLine()方法有如下说法:

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.

一行被定义为一个字符序列,后跟一个换行符(“\ n”),一个回车符(“\ r”)或一个回车符后面紧跟一个换行符(“\ r \ n”)。返回的字符串不包含终止回车符或换行符。

So the following will do the trick

所以以下方法就可以了

_content = new StringReader(sb.ToString()).ReadLine();

#5


What about

_content = sb.ToString().Trim(Environment.NewLine.ToCharArray());

#6


_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 :-)

这当然会删除“\ r \ n \ r \ n \ r \ n”以及“\ n \ n \ n \ n”和其他组合。在NewLine不是“\ n \ r”的“环境”中你可能会得到一些奇怪的行为:-)

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.

但是如果你能忍受这一点,那么我相信这是在字符串末尾删除新行字符最有效的方法。

#7


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.

这将从字符串的末尾拉出所有空格字符 - 如果您想保留非换行符空格,则只会出现问题。

#8


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.

有点不回答,但是从字符串中修剪换行的最简单方法是首先在字符串上没有换行符,确保它自己的代码永远不会看到它。也就是说,通过使用删除换行符的本机函数。如果逐行请求输出,许多流和文件/ io方法将不包括换行符,尽管可能需要在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).

像System.IO.File.ReadAllLines这样的东西大部分时间都可以代替System.IO.File.ReadAllText使用,一旦你使用正确类型的流(例如BufferedStream),可以使用ReadLine而不是Read。

#9


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

正如马库斯所指出的,TrimEnd现在正在做这项工作。我需要在Windows Phone 7.8环境中从字符串的两端获取换行符和空格。在追逐了不同的更复杂的选项后,我的问题只通过使用Trim()解决了 - 很好地通过了以下测试

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

#10


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