【问题标题】:Can't trim newline off variable in c#无法在 C# 中修剪换行符关闭变量
【发布时间】:2013-07-10 03:44:50
【问题描述】:

What is the easiest way in C# to trim a newline off of a string? 的帖子上,我看来相同的东西对他们有用,但它在我的字符串开头留下了新行。没有错误,它只是不修剪任何东西。

public formWords()
   {
   foreach (string word in someArray)
        {
            fileList += Environment.NewLine + word;
        }
        fileList.Trim(Environment.NewLine.ToCharArray());
        txtHolder.Text = fileList;
    }

我做错了什么?

提前致谢。

【问题讨论】:

  • Windows 中的NewLine 中有两个char...\r\n

标签: c# newline


【解决方案1】:

使用此代码:

fileList.ToString().Trim( '\r', '\n' );

或使用代码(jon skeet

public static string TrimNewLines(string text)
{
    while (text.EndsWith(Environment.NewLine))
    {
        text = text.Substring(0, text.Length - Environment.NewLine.Length);
    }
    return text;
}
private static readonly char[] NewLineChars = Environment.NewLine.ToCharArray();

public static string TrimNewLines(string text)
{
    return text.TrimEnd(NewLineChars);
}

【讨论】:

  • 感谢您这么快。我尝试了第一个建议。它没有用。第二个看起来它会从末端修剪,但我要修剪的是开头。
  • 可以先剪掉word再剪掉fileList>?
  • 太棒了!谢谢。现在我做错了什么是有道理的。向你竖起大拇指,好先生。
【解决方案2】:
fileList +=word + Environment.NewLine;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-06
    • 2017-09-20
    • 2015-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-18
    相关资源
    最近更新 更多