我有一个文本框,我想允许 1 个空格。所以现在,修剪方法不允许它,但是无论如何允许 1 个空格吗?
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);
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;
使用以下简单代码:
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"