简体   繁体   中英

TextBox remove leading and tailing spaces and empty lines better way

I have text box in which user may input some text. Currently I'm removing all spaces and empty lines using this code:

private void RemoveSpacesAndEmptyLines()
{
    textBox.Lines = textBox.Lines.Where(val => val.Trim().Length != 0).ToArray();
    textBox.Lines = textBox.Lines.Select(c => c.Trim()).ToArray();
}

But is it possible to do only one call?
I need to have only lines that have something except spaces in it and also remove all spaces.

But is it possible to do only one call?

Sure, because you can chain the Where and the Select :

textBox.Lines
    .Where(val => val.Trim().Length != 0)
    .Select(c => c.Trim()).ToArray();
textBox.Lines = textBox.Lines
    .Select(l => l.Trim())
    .Where(l => !string.IsNullOrEmpty(l))
    .ToArray();
function trim (el) {
    el.value = el.value.
       replace (/(^\s*)|(\s*$)/, ""). // removes leading and trailing spaces
       replace (/[ ]{2,}/gi," ").       // replaces multiple spaces with one space 
       replace (/\n +/,"\n");           // Removes spaces after newlines
    return;
}​


onkeypress="return trim(this)"

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