开发者

Remove or trim carriage return at the end of string [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicate:

Removing carriage return and new-line from the end of a string in c#

How do I remove the carriage return at the end of string. I have already google out this but I cannot find the code I need.

This is my current code:

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

but of course all the occurrence of the old character will be replaced.

I have tried these:

public string trim(string 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;

}

but is not working for me,开发者_StackOverflow社区 maybe I miss something or there's a wrong with my code

I have also try using regular expression but I can't get what I need.

I get the string from word document then will be transfered to another docs.

I'll appreciate any help.Tnx


Hi I found a solution in following link. So the credit should go to that author.

Example

However I have customized it to boost the demonstrative capability.

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

Check this out.


See this answer: Removing carriage return and new-line from the end of a string in c#

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜