文本框文本 trim 允许 1 个空格 asp net c#

textbox text trim allow 1 blankspace asp net c#

我有一个文本框,我想允许 1 个空白 space。所以现在,trim 方法不允许它,但是无论如何允许 1 个空白 space?

C#:

bool before = txtSearchFor.Text.StartsWith(" ");
bool after = txtSearchFor.Text.EndsWith(" ");
string newText = before && after
                 ? txtSearchFor.Text.Trim() + " "
                 : before ? " " + txtSearchFor.Text.TrimStart() : after ? txtSearchFor.Text.TrimEnd() + " " : txtSearchFor.Text;

var contacts = SearchNRender(ExtCatIdentifier.All.ToString(), txtSearchFor.Text = newText);
var searchFormat = string.Format("[ {0} ]", txtSearchFor.Text);

使用这个简单的代码:

string t = txtSearchFor.Text;

if (t.StartsWith(" ")) //starts is blank, end may be blank or not
    t = " " + t.Trim(); 
else if (t.EndsWith(" ")) //only end is blank
    t = t.TrimEnd() + " ";

txtSearchFor.Text = t;


//Outputs:
// "    abc def   " => " abc def"
// "abcd def      " => "abc def "
// "    abc def" => " abc def"
bool before = txtSearchFor.Text.StartsWith(" ");
bool after  = txtSearchFor.Text.EndsWith(" ");
string newText = before && after 
                 ? txtSearchFor.Text.Trim() + " " 
                 : before ? " " + txtSearchFor.Text.TrimStart() : after ? txtSearchFor.Text.TrimEnd() + " " : txtSearchFor.Text;

txtSearchFor.Text = newText;