【问题标题】:Remove or trim carriage return at the end of string [duplicate]删除或修剪字符串末尾的回车[重复]
【发布时间】:2010-12-14 03:50:40
【问题描述】:

可能重复:
Removing carriage return and new-line from the end of a string in c#

如何删除字符串末尾的回车符。 我已经用谷歌搜索过了,但找不到我需要的代码。

这是我当前的代码:

return s.Replace("\n", "").Replace("\r", "").Replace("\r\n", "").Trim();

当然,所有出现的旧字符都会被替换。

我试过这些:

公共字符串修剪(字符串 s) {

string[] whiteSpace = {"\r", "\n", "\r\n"};

foreach(string ws in whiteSpace)
{
    if (s.EndsWith(ws))
    {
        s = s.Substring(0, s.Length - 1);
    }
}
return s;

}

但对我不起作用,也许我错过了什么或者我的代码有问题

我也尝试过使用正则表达式,但我无法得到我需要的东西。

我从 word 文档中获取字符串,然后将其转移到另一个文档。

我将不胜感激。Tnx

【问题讨论】:

  • @paxdiablo 我检查了可能的重复项,但没有发现任何重复项。关于我已经检查过但对我不起作用的链接。也许我会尝试使用我在该链接中读到的正则表达式进行实验。
  • 对我来说看起来像个骗子,这两个问题都是 C#,都试图从字符串末尾删除 CR/LF。除非我遗漏了一些东西,否则这完全匹配。
  • 我也想知道为什么我会得到这样的结果。我不确定我的代码中的某个地方是否会导致意外结果,所以我尝试在修剪字符串后立即在控制台中打印它。但话又说回来,我得到了同样的结果。注意:我使用的是 C# 2010 和 office 2003 您可以查看此链接以查看实际输出:b.imagehost.org/0707/carriage_return.jpg

标签: c# regex trim


【解决方案1】:

您好,我在以下链接中找到了解决方案。所以功劳应该归于那个作者。

Example

但是我已经对其进行了自定义以增强演示能力。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication4
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            String s = "ABCDE\r\n" + "FGHIJ";
            MessageBox.Show(s);            
            MessageBox.Show(RemoveAndNewlineLineFeed(s));            
        }

        string RemoveAndNewlineLineFeed(string s)
        {
            String[] lf = { "\r", "\n" }; 
            return String.Join("",s.Split(lf,StringSplitOptions.RemoveEmptyEntries));             
        }
    }
}

看看这个。

【讨论】:

  • 我已经在我的代码中检查并使用了它。虽然它删除了回车,但它删除了所有出现的回车。我将尝试从该代码中进行试验。tnx
【解决方案2】:

【讨论】:

  • 我已经尝试过该链接,但在我的情况下它不起作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-26
  • 2016-03-21
  • 1970-01-01
  • 1970-01-01
  • 2013-09-11
相关资源
最近更新 更多