简体   繁体   中英

Remove empty space from the end of a line in a richtextbox

How can I remove empty space from end of line in a richtextbox

Original string

My code:

string[] lines2 = comparedResultRTB1.Lines;
lines2.ToString().Replace("; );",");");

Could use Regex to do the replacement. Not sure from the question exactly what you want to do. If what you want to do is to get rid of all new lines and any whitespace that appears just before them you could do it like this:

  Regex regex = new Regex(@"\s*\n");
  string input = lines2.ToString();
  string result = regex.Replace(input, "");

Add this line:

lines2 = lines2.Select(o => o.Trim()).ToArray();

So your code becomes this:

string[] lines2 = comparedResultRTB1.Lines;
lines2 = lines2.Select(o => o.Trim()).ToArray();
lines2.ToString(); // I'm assuming there is supposed to be an assignment here

If you don't want to use LINQ you can use this method:

string[] TrimLines(string[] lines) {
    var trimmedLines = new List<string>();

    foreach(var line in lines) {
        trimmedLines.Add(line.TrimEnd());
    }

    return trimmedLines.ToArray();
}

In which case your code would become this:

string[] lines2 = comparedResultRTB1.Lines;
lines2 = TrimLines(lines2);
lines2.ToString(); // I'm assuming there is supposed to be an assignment here

The problem appears to be that you have a line break in there, not just spaces.

This works as intended:

var text = "ALTER TABLE \"TBLCONCESSIONAIREOFFICES\" ADD (\"CNCO_IRISAUTOCONFIRMINVOICE\" NUMBER(" +
    "2,0) DEFAULT 0     --0: No, 1: Yes;    \r\n);";

var splitted = text.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).Select(a => a.Trim());

var result = String.Concat(splitted);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM