C#:string.Trim()不删除空格

dan*_*aki 0 c# datetime parsing trim

我有一个提示要求用户输入日期(以特定格式).然后我修剪了字符串,但是如果在我在提示框中点击"Enter"时有一个额外的空格,那么字符串在剪裁后仍然会有一个额外的空格.我也会发布我的提示框代码.我的字符串是:2015年7月29日下午1:32:01 PDT和2015年7月30日下午12:34:27 PDT

    string afterpromptvalue = Prompt.ShowDialog("Enter earliest Date and Time", "Unshipped Orders");
                    afterpromptvalue.Trim();
                    string beforepromptvalue = Prompt.ShowDialog("Enter latest Date and Time", "Unshipped Orders");
                    beforepromptvalue.Trim();

 string format = "MMM dd, yyyy h:mm:ss tt PDT";

            CultureInfo provider = CultureInfo.InvariantCulture;

            afterpromptvalue.Trim();
            beforepromptvalue.Trim();


            DateTime createdAfter = DateTime.ParseExact(afterpromptvalue, format, provider);



            DateTime createdBefore = DateTime.ParseExact(beforepromptvalue, format, provider);

public static class Prompt
{
    public static string ShowDialog(string text, string caption)
    {
        Form prompt = new Form();
        prompt.Width = 500;
        prompt.Height = 150;
        prompt.FormBorderStyle = FormBorderStyle.FixedDialog;
        prompt.Text = caption;
        prompt.StartPosition = FormStartPosition.CenterScreen;
        Label textLabel = new Label() { Left = 50, Top=20, Text=text };
        TextBox textBox = new TextBox() { Left = 50, Top=50, Width=400 };
        Button confirmation = new Button() { Text = "Ok", Left=350, Width=100, Top=70, DialogResult = DialogResult.OK };
        confirmation.Click += (sender, e) => { prompt.Close(); };
        prompt.Controls.Add(textBox);
        prompt.Controls.Add(confirmation);
        prompt.Controls.Add(textLabel);
        prompt.AcceptButton = confirmation;

        return prompt.ShowDialog() == DialogResult.OK ? textBox.Text : "";
    }
}
Run Code Online (Sandbox Code Playgroud)

Ada*_*m V 9

string.Trim返回一个新字符串.它不会更新现有变量.

字符串是不可变的 - 创建对象后无法更改字符串对象的内容

https://msdn.microsoft.com/en-us/library/362314fe.aspx

代码的正确语法是:

afterpromptvalue = afterpromptvalue.Trim();