【问题标题】:How do I remove the newlines from this string?如何从此字符串中删除换行符?
【发布时间】:2016-04-14 13:21:24
【问题描述】:

我花了很多很多时间寻找答案。如果您在此站点上查找删除新行,它会给出看起来可行的答案,但我无法让它们起作用。

string TextFileBlock = File.ReadAllText("TextFile.txt");

 char newlinechar = '\n' ;

 TextFileBlock = TextFileBlock.Replace(" ", String.Empty); //works for the spaces

 TextFileBlock = TextFileBlock.Replace(newlinechar.ToString(), String.Empty);

///Does not get rid of the newlines. The enter key.

      // TextFileBlock = TextFileBlock.Replace("\n", String.Empty);// not works
      //TextFileBlock.Replace(Environment.NewLine, string.Empty);//not works

C#问题

【问题讨论】:

  • 您知道在 Windows 上,新行由回车和换行符 \r\n 组成,而不仅仅是 \n?如果您对文件中的字符有疑问,请在十六进制编辑器中查看它,例如 HxD
  • 按照这种逻辑,OP 代码应该删除了 \n 并留下了 \r。

标签: c# newline


【解决方案1】:

假设文件相当小,您可以将整个段替换为:

string[] lines = File.ReadAllLines("TextFile.txt");
string TextFileBlock = String.Concat(lines).Replace(" ", "");

ReadAllLines 方法返回一个行数组,其中一行以回车符 (\r)、换行符 (\n) 或 CRLF (\r\n) 结束。数组中的单个元素不包括终止的回车或换行,因此在连接数组元素时不包括在最终字符串中。

【讨论】:

    【解决方案2】:

    这应该照顾它:

    public static string RemoveNewLines(this string input)
    {
        return input.Replace("\r\n", string.Empty)
                .Replace("\n", string.Empty)
                .Replace("\r", string.Empty);
    }
    

    【讨论】:

    • 最好只使用return input.Replace("\n", string.Empty).Replace("\r", string.Empty);,因为这两种方法可以处理"\r\n"
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-01
    • 2011-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-12
    相关资源
    最近更新 更多