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

C#: string.Trim() not removing white spaces

我有一个提示要求用户输入日期(以特定格式)。然后我 trim 字符串,但是如果当我在提示框中点击 'Enter' 时有一个额外的 space ,该字符串仍然会在之后出现一个额外的 space trim。我也会 post 我的提示框代码。我的字符串是:Jul 29, 2015 1:32:01 PM PDT 和 Jul 30, 2015 12:34:27 PM 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 : "";
    }
}

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

Strings are immutable--the contents of a string object cannot be changed after the object is created

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

您的代码的正确语法是:

afterpromptvalue = afterpromptvalue.Trim();

对字符串调用 Trim() 不会更改字符串本身。它 returns 字符串被修剪了。

在 C# 中,字符串不可更改。您对字符串所能做的就是为其分配一个新字符串,调用字符串上的方法不能更改原始字符串,除非您将 return 值分配给相关字符串对象。

例如,更改:

afterpromptvalue.Trim();

收件人:

afterpromptvalue = afterpromptvalue.Trim();

你也许应该试试这个 ;)

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

并阅读:

https://msdn.microsoft.com/en-gb/library/d4tt83f9(v=VS.110).aspx

也许 here 的这句话对你来说很有趣

Immutability and the StringBuilder class

A String object is called immutable (read-only), because its value cannot be modified after it has been created. Methods that appear to modify a String object actually return a new String object that contains the modification.